Wern Ancheta
Wern Ancheta

Reputation: 23297

How to know if an sql statement executed in java?

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

Answers (4)

jzd
jzd

Reputation: 23629

Use executeUpdate() to get row counts.

Also some major items need correction in your code:

  • You are not using PreparedStatement correctly. Use parameters instead.
  • Don't swallow exceptions. At the least print a stack trace but showing a message to the user would be nice.
  • You are running the statement twice. Just do it once in your if statement.

Upvotes: 1

matt b
matt b

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

Hiro2k
Hiro2k

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

Geo
Geo

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

Related Questions