Update changes In JTable to database?

122 views Asked by At

It's not working. Using the select syntax put table to JTable. Then I want update the changes in JTable to the Database. It's a reasonable idea, if there is an better idea to Update GUI changes to database, please let me know. The following is my code after wondering other people's idea. Now I am only dealing with Updates, Insert/Delete would be harder. Any full tutorial links recommend? I step by step following this link(How to insert, update and delete items from JTable that is loaded from (SQLite) Database)

Edit1: String updatequery = "update emp set department= ? where name = ?"; this one works. But it can only update the department column

Edit2: Now all works fine, but all is based on datatype. When I accidentally mouse touched wrong column. Then there is lots error message.Bacause i use setInt, setString to update table.

public paintSpecificTableCells() throws SQLException {
        TableModel model = initTableModel();
        JTable table = new JTable(model);
        table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        model.addTableModelListener(new TableModelListener(){
            @Override
            public void tableChanged(TableModelEvent e) {
                int rowFirstIndex = e.getFirstRow();
                int rowLastIndex = e.getLastRow();
                DefaultTableModel model = (DefaultTableModel) e.getSource();

                if(e.getType()==TableModelEvent.UPDATE){
                    int updatedColIndex = e.getColumn();
                    String updateColumn =  table.getColumnName(updatedColIndex);
                    String updatedValue = (String) model.getValueAt(rowFirstIndex, updatedColIndex);
                    String relatedID = (String) model.getValueAt(rowFirstIndex,1);
                    System.out.println("column: "+updateColumn+"  updated value is: "+updatedValue);
                    System.out.println("primary key name is : "+ model.getColumnName(1) +" value: "+relatedID);
                    //column: department  updated value is: Shipping
                    //primary key name is : name value: Dylan
                    String updatequery = "update emp set"+updateColumn+ "="+ "?" +" where name = ?";
                    int affectedrows = 1;

                    try {
                        PreparedStatement pstmt = Main.connection.prepareStatement(updatequery);
                        pstmt.setString(1,updatedValue );
                        pstmt.setString(2, relatedID);
                        affectedrows = pstmt.executeUpdate();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                   // return affectedrows;
                }
            }
        });
0

There are 0 answers