如何在JTable和mysql中删除一行

时间:2016-02-21 03:40:19

标签: java swing jtable

Java代码

int dialogDelete=JOptionPane.showConfirmDialog(null,"Are you sure you want to delete this Personnel?", "DELETE PERSONNEL",JOptionPane.YES_NO_OPTION);
            if(dialogDelete==JOptionPane.YES_OPTION){      
                DefaultTableModel model = (DefaultTableModel)tbl_personnel.getModel();
                int row = tbl_personnel.getSelectedRow();



                String url = "jdbc:mysql://localhost/mypos";
                String username = "root";
                String password = "";

            try {
                Connection connection = DriverManager.getConnection(url,username,password);
                System.out.println("database connected");
                stmt = connection.createStatement();

                stmt.execute("DELETE FROM Personnel WHERE Id ="+row+"");         
            } catch(Exception e) {
                throw new IllegalStateException("cannot",e);
            }      

                int modelRow = tbl_personnel.convertRowIndexToModel( row );
                model.removeRow( modelRow );


            }

我编辑了代码。我现在可以删除JTable中的行并删除mysql中的一行,但是在JTable中删除的行不是mysql中删除的行。我不确定是什么问题。

1 个答案:

答案 0 :(得分:2)

  

我想知道当我点击JTable上的一行然后按下删除按钮时如何从JTable中删除一行。

您不需要MouseListener。默认情况下将选中该行。

您也不会在按钮上使用MouseListener。相反,您需要在“删除行”按钮中添加ActionListner

您可能正在使用DefaultTableModel,因此您可以使用模型的removeRow(...)方法从表中删除行。

ActionListener中的基本代码如下:

DefaultTableModel model = (DefaultTableModel)table.getModel();
int row = table.getSelectedRow();
int modelRow = table.convertRowIndexToModel( row );
model.removeRow( modelRow );

所以基本上你拿出显示JOptionPane的当前代码,如果响应为YES则添加上面的代码。

编辑:

stmt.execute("DELETE FROM Personnel WHERE Id ="+row+"");         

您不能使用“选定的行来控制要删除的记录。”选定的行表示JTable中的行位置,而不是数据库表中定义的行的ID。

TableModel中必须有一列表示行的ID。所以代码就像:

String id = table.getValueAt(row, column);
stmt.execute("DELETE FROM Personnel WHERE Id =" + id + "");       

最好使用PreparedStatement。你不太喜欢犯SQL语法错误:

String sql = "DELETE FROM Personnel WHERE Id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, id );
stmt.executeUpdate();
stmt.close();
相关问题