0

看看这段代码:

ResultSet results=preparedStmt.executeQuery();

while (results.next()){
   String subject=results.getString(1);
   System.out.println(subject +" 1st time");
}

while (results.next()){
   String subject=results.getString(1);             
   System.out.println(subject+ " 2nd time");
}

为什么系统第一次只打印结果,第二次不打印结果?

如果我们想运行 results.next() 超过 1 次,那么正确的编码方式是什么?

4

2 回答 2

3

您没有运行 .next() 一次。单个 while 循环将多次运行它,直到您到达结果集的末尾。当到达第二个 while 循环时,结果集中没有任何东西可以重复:你已经结束了。您必须再次运行查询才能重新开始或生成可滚动的结果集

       Statement stmt = con.createStatement(
                                      ResultSet.TYPE_SCROLL_INSENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);
       ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
       // rs will be scrollable, will not show changes made by others,
       // and will be updatable

并打电话rs.first()

于 2013-04-18T01:33:13.637 回答
1

while( rs.next() )会将“当前行”光标前进到集合的末尾。

默认情况下,aResultSet是只读的并且只转发,所以一旦你到达最后,你需要调用 first() 重新开始。注意:first()是一种可选方法,您的驱动程序可能不支持。

于 2013-04-18T01:32:18.817 回答