Reputation: 45
im making a java swing project , ive connected to my database and calling all the values into a JTable , in my frame when you click on a row in the Jtable and click the delete button then the value is deleted , but i have a bug because if you try to delete a value(example if u delete the number 1) and there is another same value(number 1) in the jtable then both of them will delete
I think the problem is in this code
public void mouseClicked(MouseEvent arg0) {
try {
int row = table.getSelectedRow();
String Description = (table.getModel().getValueAt(row, 1)).toString();
String query = "select * from PostNotice where Description='" + Description + "'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
textArea.setText(rs.getString("Description"));
}
pst.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is for the delete
public void actionPerformed(ActionEvent e) {
String query = "Delete from PostNotice where Description =?";
try {
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textArea.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Post Deleted");
pst.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
textArea.setText("");
textArea.requestFocus();
refreshtable();
}
});
Upvotes: 0
Views: 115
Reputation: 57381
Actually you have to keep reference to ID (or another primary key) and delete record by the primary key value.
For you code it means e.g. Long id
class' field and store the id from DB to the field
textArea.setText(rs.getString("Description"));
id=rs.getLong("id");
Then you can use the id
to delete
String query = "Delete from PostNotice where id=?";
...
pst.setLong(1, id);
Upvotes: 1