2013-02-08 139 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