Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if an sql statement executed in java?

Tags:

java

mysql

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) {
        }
    }
like image 876
Wern Ancheta Avatar asked Mar 17 '26 20:03

Wern Ancheta


1 Answers

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);
}
like image 194
matt b Avatar answered Mar 19 '26 08:03

matt b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!