【问题标题】:Multiple rows deleting in jtable with the same value在jtable中删除具有相同值的多行
【发布时间】:2015-01-08 11:03:02
【问题描述】:

我正在制作一个 java swing 项目,我连接到我的数据库并将所有值调用到一个 JTable 中,当您单击 Jtable 中的一行并单击删除按钮时,我的框架中的值被删除,但我有一个错误,因为如果您尝试删除一个值(例如,如果您删除数字 1)并且 jtable 中有另一个相同的值(数字 1),那么它们都会删除

我认为问题出在这段代码中

  public void mouseClicked(MouseEvent arg0) {
            try {
                int row = table.getSelectedRow();
                String Description = (table.getModel().getValueAt(row, 1)).toString();

                String query = "select * from PostNotice where Description='" + Description + "'";
                PreparedStatement pst = connection.prepareStatement(query);

                ResultSet rs = pst.executeQuery();

                while (rs.next()) {
                    textArea.setText(rs.getString("Description"));
                }

                pst.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

这是为了删除

     public void actionPerformed(ActionEvent e) {


             String query = "Delete from PostNotice where Description =?";
            try {

                PreparedStatement pst = connection.prepareStatement(query);
                pst.setString(1, textArea.getText());
                pst.execute();
                JOptionPane.showMessageDialog(null, "Post Deleted");

                pst.close();

            } catch (Exception ex) 
            {
                ex.printStackTrace();
            }
            textArea.setText("");
            textArea.requestFocus();
            refreshtable();
        }

    });

【问题讨论】:

  • 删除查询在哪里?还是删除逻辑?

标签: java swing jtable


【解决方案1】:

实际上你必须保持对ID(或另一个主键)的引用并通过主键值删除记录。

对于您的代码,这意味着例如Long idclass'字段并将ID从DB存储到字段

textArea.setText(rs.getString("Description"));
id=rs.getLong("id");

然后可以使用id删除

String query = "Delete from PostNotice where id=?";
...
pst.setLong(1, id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2017-11-07
    • 2017-03-02
    • 2018-08-18
    相关资源
    最近更新 更多