简体   繁体   English

我怎样才能实现这个代码?

[英]How can I achieve this code?

Hey I have a problem with my java codes.嘿,我的 Java 代码有问题。 If I enter a text in my IDFiELD and then press the "Enter" And then message come out "ID wasn't recognize, Try again..." but it shows the values in my table.如果我在我的 IDFiELD 中输入一个文本,然后按“Enter”然后会出现消息“ID 无法识别,请再试一次...”但它显示了我表中的值。 So how can i address that problem.那么我该如何解决这个问题。

So here is my code in java eclipse:所以这是我在 java eclipse 中的代码:

IDField.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent evnt) {
            if (evnt.getKeyCode() == KeyEvent.VK_ENTER) {
                try {
                    String query = "select * from employee where IDNo = ?";
                    PreparedStatement pst = connection.prepareStatement(query);
                    pst.setString(1, IDField.getText());
                    ResultSet rs = pst.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));

                    int count = 0;
                    while (rs.next()) {
                        count += 1;
                    }
                    if (count == 1) {
                        JOptionPane.showMessageDialog(null, "ID Verified!");

                        IDField.setText(null);
                    } else {
                        JOptionPane.showMessageDialog(null, "ID was'nt recognize, Try again...");
                    }
                    rs.close();
                    pst.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, e);
                }
            }

        }
    });

I hope you can help me.我希望你能帮助我。 Thanks.谢谢。

Your method table.setModel(DbUtils.resultSetToTableModel(rs));你的方法table.setModel(DbUtils.resultSetToTableModel(rs)); consumes the ResultSet already, so you cannot use it again to count how many results you received.已经消耗了 ResultSet,因此您无法再次使用它来计算收到的结果数量。

You can:你可以:

  • run the query twice (simplest to code, but least clean and efficient)运行查询两次(最简单的编码,但最不干净和高效)
  • query the table model to see if there are rows查询表模型看是否有行
  • extract the results of the query into a datastructure and convert that to your table model and also use it to check if there were results将查询结果提取到数据结构中并将其转换为您的表模型,并使用它来检查是否有结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM