2013-04-28 26 views
2

我有以下代碼來查詢數據庫!但是while循環內的代碼不會被執行!沒有消息框,只是沒有得到執行!誰能幫我!結果集不是空的!當我從try catch塊中輸出相同的值時,它會被執行並且打印出正確的值! Th數據庫連接是一個標準的MySQL數據庫連接類!結果集代碼沒有得到執行

database = new DBConnection(); 

    String dept = txtSearch.getText(); 
    String Query = "SELECT * FROM department where dept_name= '" + dept + "'"; 

    ResultSet set = database.queryDatabase(Query); 

    try { 
     if (set.next() == false) { 
      JOptionPane.showMessageDialog(null, "No Matchs found for the search query! Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE); 
     } else { 
      while (set.next()) { 
       System.out.print(set.getString("dept_name")); 
       txtName.setText(set.getString("dept_name")); 
       txtDes.setText(set.getString("dept_desc")); 
      } 
     } 
    } catch (SQLException ex) { 
     JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getCause().toString(), JOptionPane.ERROR_MESSAGE); 
    } 

回答

4

你通過調用set.next()投出您的查詢的第一行,然後忽略排在這裏的數據:

if (set.next() == false) { // ***** here on this line 
     JOptionPane.showMessageDialog(null, "No Matchs found for the search query! 
      Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE); 
    } else { 
     while (set.next()) { 
      System.out.print(set.getString("dept_name")); 
      txtName.setText(set.getString("dept_name")); 
      txtDes.setText(set.getString("dept_desc")); 
     } 
    } 

而是一定要從你每次你ResultSet中提取信息請致電next()並且它返回true。

你可以做這樣的事情,而不是:

int setCount = 0; 
while (set.next()) { 
    setCount++; 
    System.out.print(set.getString("dept_name")); 
    txtName.setText(set.getString("dept_name")); 
    txtDes.setText(set.getString("dept_desc")); 
} 
if (setCount == 0) { 
    // show a warning to the user that the result set was empty 
} 
+0

謝謝! :)雖然我想檢查條件,我發現另一種方式來解決它! :) 謝謝! – 2013-04-28 04:17:44

+0

@DimalChandrasiri:不客氣!你如何檢查ResultSet不是空的? – 2013-04-28 04:18:20

+0

我不檢查結果集。相反,我檢查文本字段是否爲空! – 2013-04-28 04:20:39