结果集代码未执行

时间:2013-04-28 03:58:52

标签: java mysql sql database resultset

我有以下代码来查询数据库!但是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);
    }

1 个答案:

答案 0 :(得分: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"));
        }
    }

相反,每次调用next()时都要确保从ResultSet中提取信息,并返回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
}