2013-02-08 143 views
0

在下面的代码片段中,我执行查询并将结果集传递给set。然后set被分配给set1。之后有一个while循环直到set.next返回false。是否如果set.next循环后返回false,set1也将返回false?set1为空时为什么set1为空?

ResultSet set = statement.executeQuery(); 
ResultSet set1 = set; 
while (set.next()) { 
    if (set.getString(1).equalsIgnoreCase(keyword)) { 
     // If the search matches the exact keyword 
     list.put(set.getString(2), set.getString(1)); 
     // Where key is the name of the node and value is, name of the file 
    } 
} 

我问这是因为:

while (set1.next()) { 
    System.out.println("@@@Inside the while [email protected]@@"); 
    if (set1.getString(1).contains(keyword) 
    && set1.getString(1).compareToIgnoreCase(keyword) !=0) { 
     // If the search contains the keyword but does not exactly match 
     list.put(set.getString(2), set.getString(1)); 
     // Where key is the name of the node and value is, name of the file 
     System.out.println("@@@Inside the if statement of second while loop [email protected]@@"); 
    } 
} 

while结构永远不会奏效。这是原因吗?如果是这样,我该怎么办?

+2

您已经遍历ResultSet。请理解,虽然有两个ResultSet *变量*,但它们都引用相同的ResultSet *对象*。所以如果你迭代了这个对象,并且在这个变量上调用'next()'返回false,那么无论你调用哪个变量,它都是false。 – 2013-02-08 18:19:56

+0

@HovercraftFullOfEels但我在迭代之前将'set'分配给了'set1' – saplingPro 2013-02-08 18:22:23

+1

没关系。再次set和set1指的是同一个对象。 – 2013-02-08 18:23:03

回答

1

你有两个主要缺陷:

  1. 分配setset1不会使一个副本 - 这是一组相同的
  2. String.contains()区分大小写(代码不符合您的评论)

修复的方法是:

  1. 不要使用两个循环 - 只使用一个循环
  2. 使用`toLowerCase()与实现了“不区分大小写包含”测试
  3. 另外,如果你的第一个测试是真实的,那么就是你的第二个,所以你不”吨需要两个测试/循环反正

试试这个代码:

ResultSet set = statement.executeQuery(); 
    while(set.next()) { 
     if(set.getString(1).toLowerCase() 
       .contains(keyword.toLowerCase)) { 
      list.put(set.getString(2), set.getString(1)); 
     } 
    } 

而且,不叫图“清单” - 称之为“地图”,否则它只是要来迷惑读者你的代码。

0

你可以尝试这样做。

ResultSet set1 = statement.executeQuery(); 
0

set1是到同一个对象,该对象set点到参考。如果您想再次遍历ResultSet,您需要将迭代器光标移动到开始再次使用类似:

set.beforeFirst(); 

在Java中,分配变量的对象不会使对象的副本,它只会引用内存中的对象。如果您想使setset1独立工作,则必须明确制作该对象的副本。

在您的特定用例中,我不认为这就是您想要的,只是移动迭代游标似乎更好。

+0

如果你绝对必须得到'ResultSet'对象的副本,我会建议看看这个问题:http://stackoverflow.com/questions/3817785/copying-java-resultset – 2013-02-08 18:30:15

0

是不是,如果在循环后set.next返回false,set1还将 返回false?

。因为set1指的是set所指的Resultset的同一个对象。因此,对象set引用的任何行为也将反映为set1。在您的第一个while循环中,set引用的ResultSet对象在迭代到所有记录(使用set.next())后会完全耗尽。此后,无论哪个变量(set或set1)试图读取更多,都将得到.next()false

如果在你的第一个while循环构造中,我使用set变量检查.next()变量,并使用set1变量得到结果,它仍然可以工作。 试试这个代码,而不是你的第一个结构,你会看到,输出是一样的你已经写在你的第一while结构:

ResultSet set = statement.executeQuery(); 
     ResultSet set1 = set; 
     while(set.next()) { 
      if(set1.getString(1).equalsIgnoreCase(keyword)) { // If the search matches the exact keyword 
       list.put(set1.getString(2), set1.getString(1)); 
       // Where key is the name of the node and value is, name of the file 
      } 
     } 

如果你仍然想set1返回的结果,你应该重新构建一个新的ResultSet使用对象:

set1 = stat.executeQuery() 

其中,stat是无论你是使用在代码中Statement/PreparedStatement