2

我有以下代码来查询数据库!但是while循环内的代码没有被执行!没有消息框,只是没有被执行!谁能帮我!结果集不为空!当我从 try catch 块中打印出相同的值时,它会被执行并打印出正确的值!数据库连接是标准的 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

1 回答 1

4

You're throwing out the first row of your query by calling set.next() and then ignoring the data in the row here:

    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"));
        }
    }

Instead be sure to extract information from your ResultSet every time you call next() and it returns true.

You could do something like this instead:

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
}
于 2013-04-28T04:07:39.027 回答