【问题标题】:Result set code doesn't get executed结果集代码未执行
【发布时间】:2013-04-21 23:40:03
【问题描述】:

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

【问题讨论】:

    标签: java mysql sql database resultset


    【解决方案1】:

    调用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
    }
    

    【讨论】:

    • 谢谢! :) 虽然我想要检查条件,但我找到了另一种绕过它的方法! :) 谢谢!
    • @DimalChandrasiri:不客气!如何检查 ResultSet 不为空?
    • 我不检查结果集。相反,我检查文本字段是否为空!
    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2014-06-29
    • 2011-04-03
    相关资源
    最近更新 更多