如何解析结果集的 .equals 函数的值?

显示我的 jFrame 的图像

我正在制作一个框架,它使用如图所示的文本字段逐一显示 sql 表中的记录。在编写下一个按钮的代码时,我需要知道结果集的位置以转到下一条记录。为此,我使用了带有“if”条件的 do-while 循环。以下是我的代码:

try{

        Connection conn=null;

        Statement stmt=null;

        ResultSet rs=null;

        String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";

        conn=DriverManager.getConnection(url,userid,pwd);

        stmt=conn.createStatement();

        String query="select * from emp;";

        rs=stmt.executeQuery(query);

        String search=jTextField1.getText();

        String search1=jTextField2.getText();

        double search2=Double.parseDouble(jTextField3.getText());

        String search3=jTextField3.getText();

        rs.first();

        do{

            if(rs.equals(new Object[] {search, search1, search2, search3}))

                break;

        }while(rs.next());

        rs.next();

        String nm=rs.getString("Name");

        String desg=rs.getString("Designation");

        double pay=rs.getDouble("Pay");

        String city=rs.getString("City");

        jTextField1.setText(nm);

        jTextField2.setText(desg);

        jTextField3.setText(pay + "");

        jTextField4.setText(city);

    }catch(Exception e){

        JOptionPane.showMessageDialog(null, e.getMessage());

    }

但它显示“结果集结束后”错误。请在这件事上给予我帮助。也欢迎任何使我的代码变得更好的建议。提前致谢!!


慕斯709654
浏览 29回答 1
1回答

当年话下

您不能用于ResultSet.equals此目的,因为这不是Object.equals合同的用途。它用于检查一个对象是否等于相同(或至少兼容)类型的另一个对象。因此, AResultSet永远不会等于对象值数组。看起来您想从表中选择与emp您的搜索值匹配的一行,在这种情况下,正确的解决方案是仅向数据库询问该行。选择所有行然后在 Java 应用程序中进行过滤效率非常低,因为数据库必须将所有行发送到您的应用程序,而查找数据正是数据库所擅长的。相反,您应该使用带有准备好的语句的 where 子句:try (Connection connection = DriverManager.getConnection(url, userid, pwd);     PreparedStatement pstmt = connection.prepareStatement(         "select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {   pstmt.setString(1, search);   pstmt.setString(2, search1);   pstmt.setDouble(3, search2);   pstmt.setString(4, search3);   try (ResultSet rs = pstmt.executeQuery()) {       if (rs.next() {           String nm = rs.getString("Name");           String desg = rs.getString("Designation");           double pay = rs.getDouble("Pay");           String city = rs.getString("City");           jTextField1.setText(nm);           jTextField2.setText(desg);           jTextField3.setText(String.valueOf(pay));           jTextField4.setText(city);       } else {           // handle not found case       }   } }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java