0

I have a JTable bound to MySQL. I already have done code to insert data.

But i don't know how to delete.

I have this sample delete method that works in other simple projects.

public String deleteItem(String name) {

    String answer = "";
    try {
        Connection con = Connect.getConnection();
        String sql = "Delete FROM item where name = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, name);

        ps.executeUpdate();

        ps.close();
        con.close();

        answer = "OK";
    } catch (Exception e) {
        answer = e.toString();
    }

    return answer;
}

Even when I worked with an unbound table I have done this remove row from jtable that did well for me.

But now its a table bound to MySQL and I can't find a way to delete row... already searched on the internet. Found nothing.

PS: i'm using netbeans. i right-clicked jtable > bind > elements , to bind table.

Slaled
  • 1
  • 2

1 Answers1

0

Oh, I found a way!

First, I changed my deleteItem method, to delete by id

ItemDAO.java

public String deleteItem(int ID_item) {
    
    String answer = "";
    try {
        Connection con = Connect.getConnection();
        String sql = "Delete FROM item where ID_Item = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, ID_item);

        ps.executeUpdate();
        
        ps.close();
        con.close();

        answer = "OK";
    } catch (Exception e) {
        answer = e.toString();
    }

    return answer;
}

Then the action in delete button goes like this.

Form.java

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                           
     int column = 0;    // get the first column which is ID_Item
     int row = tableItem.getSelectedRow();  //get row selected by user
     int value = (int) tableItem.getModel().getValueAt(row, column); // store ID_Item value
     String answer = new ItemDAO().deleteItem(value);  // call up deleteItem method
             
     if(answer.equals("OK")) {
         System.out.println("OK"); // just for test
         itemList.clear();    // this is needed to update the bound table after Insert/Delete/Update etc
         itemList.addAll(itemQuery.getResultList()); // same as above comment
     }else{
         System.out.println("ERROR"); // just for test.
     } 

Maybe isn't the most beautiful way to do it, but it works.

Community
  • 1
  • 1
Slaled
  • 1
  • 2