Java While循环数据库

时间:2015-02-22 10:32:41

标签: java mysql while-loop

我在下面的代码中有两个循环。问题是第一个循环只迭代一次。它没有显示所有数据。

st = conn.createStatement();
rs = st.executeQuery("SELECT * from geopools");           
while(rs.next()){
   System.out.println(rs.getInt("id"));
   rs = st.executeQuery("SELECT * from Geofields where id_pool='"+rs.getInt("id")+"'");
   while (rs.next()) {
         System.out.println(rs.getString("name")+"//");
   }
}

3 个答案:

答案 0 :(得分:3)

这是因为你使用相同的ResultSet。第二次迭代使用单独的ResultSet

st = conn.createStatement();
rs = st.executeQuery("SELECT * from geopools");           
while(rs.next()){
   System.out.println(rs.getInt("id"));
   ResultSet rs2 = st.executeQuery("SELECT * from Geofields where id_pool='"+rs.getInt("id")+"'");
   while (rs2.next()) {
         System.out.println(rs2.getString("name")+"//");
   }
}

答案 1 :(得分:1)

是。您的第二个循环使用ResultSet

想象一下,您正在从1循环到10

int i = 1;
for(; i <= 10; ++i) {
    doStuff();
}

很明显doStuff()执行10次。现在我们将其更改为您的循环:

int i = 1;
for(; i <= 10; ++i) {
    doStuff();
    for(; i <= 10; ++i) {
        doOtherStuff();
    }
}

现在doStuff执行一次,然后我们进入内循环。这将执行10次并递增i。当内循环退出时,i11并且满足外循环条件,它会立即退出。

你正在(差不多)完全做同样的事情,而不是i你有一个ResultSet,它有很多行。第一个循环占用一行,并从该行打印id。然后内循环消耗其余的行。

答案 2 :(得分:0)

它工作得很好,但是当我添加第三个循环时,我遇到了同样的问题,这是我的源代码:

st = conn.createStatement();
rs = st.executeQuery("SELECT * from geopools");   
int idPool=0;
int idField =0;
while(rs.next()){
     DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("Pool : "+rs.getString("name"));
     poolNode.add(treeNode);
     idPool = rs.getInt("id");

     st2 = conn.createStatement();
     rs2 = st2.executeQuery("SELECT * from Geofields where id_pool='"+idPool+"'");
     while (rs2.next()) {                    
          DefaultMutableTreeNode fieldsNode = new DefaultMutableTreeNode("Field : "+rs2.getString("name"));
          treeNode.add(fieldsNode);
          idField = rs2.getInt("id");

          st3 = conn.createStatement();
          rs3 = st3.executeQuery("SELECT * from geofieldsproject where id_pool='"+idPool+"'");
          while (rs3.next()) {
                DefaultMutableTreeNode projectsNode = new DefaultMutableTreeNode("Field : "+rs3.getString("name"));
                treeNode.add(projectsNode);                    
           }  
     }
 }            

 st = null;
 rs = null;
 st2 = null;
 rs2 = null;
 st3 = null;
 rs3 = null;