Java遞歸調用

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();
  }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章