Reputation: 23297
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) {
}
}
Upvotes: 2
Views: 9772
Reputation: 23629
Use executeUpdate() to get row counts.
Also some major items need correction in your code:
PreparedStatement
correctly. Use parameters instead.Upvotes: 1
Reputation: 139931
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);
}
Upvotes: 10
Reputation: 5587
You should replace createPlayer.execute(); for a createPlayer.executeUpdate which returns an int that represents the number the number of rows that were affected. What you need to do is save that in an int and then compare if it's 0.
Upvotes: 2
Reputation: 96807
Use executeUpdate. It returns an int parameter telling you the number of rows affected. Also, be careful, in your code you are executing the statement twice.
Upvotes: 6