开发者

How to know if an sql statement executed in java?

开发者 https://www.devze.com 2023-02-17 08:40 出处:网络
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?

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!");

开发者_JS百科            }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);
}


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.


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.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号