Java递归调用

来源:互联网 发布:android编程权威指南2 编辑:程序博客网 时间:2024/06/04 17:59

DAO

public List<Com> getComByPid(int pid) throws SQLException{
  String url="jdbc:mysql://localhost:3306/test";
  Connection con = DriverManager.getConnection(url, "root", "123456");
  List<Com> coms = new ArrayList<Com>();
  try{
   Statement st = con.createStatement();
   ResultSet rs= st.executeQuery("select * from com where pid ="+pid);
   while(rs.next()){
    Com com = new Com();
    com.setId(rs.getInt("id"));
    com.setCname(rs.getString("cname"));
    com.setPid(rs.getInt("pid"));
    coms.add(com);
   }
   rs.close();
   
   st.close();
  }
  catch(Exception ex){
   ex.printStackTrace();
  }
  finally{
   con.close();
  }
  return coms;
 }

Service

ComDao cdao = new ComDao();
 public List<Com> findComPid(int pid, List<Com> cs) throws SQLException{
  
  List<Com> coms= cdao.getComByPid(pid);
  for(Com com:coms){
   cs.add(com);
   coms=findComPid(com.getId(),cs);
  }
  return cs;
 }

UI

 ComService coms = new ComService();
  
   try {
    List<Com> tco = new ArrayList<Com>();
   List<Com> cs= coms.findComPid(2,tco);
   for(Com t:cs){
    System.out.println(t.getId()+"  "+t.getCname()+"  "+t.getPid());
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

0 0