Skip to content
Advertisement

Update cell in jTable using SQL

I want to know how I can update specific cells in jTable (in Java) using SQL.

This my try but it doesn’t work.

public void actionPerformed(ActionEvent e) {
    int sel_tab=jTable1.getSelectedRow();

    myDbConnection dbconnect;
    dbconnect = new myDbConnection();
        ResultSet resultSet =null;
        resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 FROM pledges ");     
   if(e.getSource()==jButton1){
        try {
        String n = resultSet.getString("id");
        String a = resultSet.getString("area");
        String p = resultSet.getString("location");
        String se = resultSet.getString("status1");
            dbconnect.excuteUpdate("update pledges SET area="+ a +" whare id= "+sel_tab+"");
        } catch (SQLException ex) {;}
   }
}

Note: I am working in Netbeans.

Advertisement

Answer

finally I’ve found the correct answer

the following code will explain every thing

  public void actionPerformed(ActionEvent e) {


   if(e.getSource()==jButton1){



               jTable1.getModel().addTableModelListener(new TableModelListener() {
  public void tableChanged(TableModelEvent e) {
      myDbConnection dbconnect;
    dbconnect = new myDbConnection();
         ResultSet resultSet =null;
        resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 FROM pledges ");
       int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object data = model.getValueAt(row, column);
    int viewRow = jTable1.getSelectedRow(); // view row with sort
    int modelRow = jTable1.convertRowIndexToModel(viewRow); // convert
    dbconnect.excuteUpdate("update pledges set area ='" + data + "' where id = '"+jTable1.getModel().getValueAt(modelRow,0) +"'"  );
      System.out.println("Table value changed "+data);
  }
});

thanks for every one helped me

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement