2013-04-28 59 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