如何从DB和JTable中删除选定的行?

时间:2017-04-30 20:33:36

标签: java mysql arrays swing jdbc

在此代码中它只删除JTable中的行,我想从DB中删除 并在运行时从JTable删除并删除错误: java.lang.ArrayIndexOutOfBoundsException: 2 >= 2但不是从DB中删除如何解决这个问题?

    private final JPanel panel_09 = new JPanel();
    JScrollPane scrollPane_09 = new JScrollPane();
    final DefaultTableModel TableModel09 = new DefaultTableModel(new String[]{"Picture", "Item", "Price", "After Discount"}, 0);
    final JTable table_09 = new JTable(TableModel09);
    JButton btnNewButton_09 = new JButton("Delete Item");

    btnNewButton_09.addActionListener ( new ActionListener() {


    public void actionPerformed(ActionEvent arg0) {
        try {
            int selectedPlanet = table_09.getSelectedRow();
            TableModel09.removeRow((int) selectedPlanet);
            Object desc = table_09.getModel().getValueAt(selectedPlanet, 4);
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123");
            String query = "delete from flyer_item where discount=desc";
            java.sql.PreparedStatement ps = conn.prepareStatement(query);
            ps.setString(1, (String) desc);
            ps.executeUpdate();

        } catch (Exception ex) {
            System.err.println(ex);
        }

    }
}
);

1 个答案:

答案 0 :(得分:2)

在获得desc

之前,您已从模型中删除了对象
int selectedPlanet = table_09.getSelectedRow();//<<--this will equal 2

TableModel09.removeRow((int) selectedPlanet);//<<----remove 2

所以现在

Object desc = table_09.getModel().getValueAt(selectedPlanet, 4);
//when you try to `getValueAt(2,4)` you get this error 
//"java.lang.ArrayIndexOutOfBoundsException: 2 >= 2"

要避免此问题,请在删除行之前获取对象:

int selectedPlanet = table_09.getSelectedRow();
Object desc = table_09.getModel().getValueAt(selectedPlanet, 4);
TableModel09.removeRow((int) selectedPlanet);

然后,您将收到另一个SQL错误,因为要将Parameters设置为PreparedStatement,您必须使用?

String query="delete from flyer_item where discount = ?";
//----------------------------------------------------^
java.sql.PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,(String) desc);