从JTable和数据库中删除行

时间:2015-07-26 18:38:37

标签: java swing jtable

我想从Jtable和数据库中删除选定的行数据。

我的代码:

 try {

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.removeRow(jTable1.getSelectedRow());

        Class.forName("org.sqlite.JDBC");
        Connection con = DriverManager.getConnection("jdbc:sqlite:C:\\management.db");
        Statement st = con.createStatement();
        int id = jTable1.getSelectedRow();
        Object number =  jTable1.getValueAt(id-1,0);
        String sql = "delete  from emp_details where id ="+number;
        int res = st.executeUpdate(sql);
        if(res == 1) {
                JOptionPane.showMessageDialog(this, "Deleted", "Emp Details", WIDTH);
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Empsearch.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Empsearch.class.getName()).log(Level.SEVERE, null, ex);
    }

当我运行程序时,获得以下异常:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -2

1 个答案:

答案 0 :(得分:0)

当调用removeRow()时,任何行选择都会被撤消,因此对getSelectedRow()的后续调用将返回-1,从而将id设置为-1。这导致getValueAt将id-1(即-2)作为其第一个参数,当然这是一个无效的行索引,因此例外。
也许尝试执行SQL更新,然后删除表格行?

相关问题