I want to know if this delete statement has actually deleted something. The code below always execute the else. Whether it has deleted something or not. What's the proper way to do this?
public Deleter(String pname, String pword) {
try {
PreparedStatement createPlayer = conn.prepareStatement("DELETE FROM players WHERE P_Name='"+ pname +"' AND P_Word='" + pword + "'");
createPlayer.execute();
if(createPlayer.execute()==true){
JOptionPane.showMessageDialog(null, "Player successfully deleted!");
}else{
JOptionPane.showMessageDialog(null, "Player does not exist!", "notdeleted", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
}
}
You are actually executing the delete statement twice, since you call .execute() twice. In most situations, you're not likely to have data that can be deleted by the statement if you run it almost immediately a second time.
Instead, use the executeUpdate() method which returns to you the number of rows modified:
int rowsAffected = createPlayer.executeUpdate();
if(rowsAffected > 0) {
JOptionPane.showMessageDialog(null, "Player successfully deleted!");
}
else{
JOptionPane.showMessageDialog(null, "Player does not exist!", "notdeleted", JOptionPane.ERROR_MESSAGE);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With