1

我这里有一个工作代码,当您调用 removeUser 方法时,它会从数据库中删除用户。:

public void removeUser(String username)
    {

        try {
            pstmnt = conn.prepareStatement("DELETE FROM user_info WHERE username = ?");
            pstmnt.setString(1, username);
            pstmnt.executeUpdate();

            pstmnt = conn.prepareStatement("DELETE FROM users WHERE username = ?");
            pstmnt.setString(1, username);
            pstmnt.executeUpdate();



            //pstmnt.executeBatch();
            System.out.println("Removed User :" + username);
        } catch (SQLException e) {System.out.println("Error: " + e.getMessage()); }
    }

但是,我需要在删除用户之前确保用户存在,否则打印用户不存在。如何实现?

4

3 回答 3

4

您可以改为使用 的结果pstmnt.executeUpdate()来确定 SQLDELETE操作是否成功:

int rowsUpdated = pstmnt.executeUpdate();
if (rowsUpdated == 0) {
    System.out.println("User does not exist");
} else {
    System.out.println("User deleted");
}
于 2013-06-18T16:38:42.813 回答
1

pstmnt.executeUpdate()返回行数。这表示删除了多少行!

因此,如果它的值为零,则显示 message user does not exist.

于 2013-06-18T16:41:26.367 回答
1

调用 executeUpdate 将返回调用修改的行数。做这样的事情:

          pstmnt = conn.prepareStatement("DELETE FROM users WHERE username = ?");
          pstmnt.setString(1, username);
          int rows = pstmnt.executeUpdate();
          if (rows == 0) {  
              //record does not exist 
              System.out.println("User does not exist");
          } else if (rows > 0) {  
              //there were # of rows deleted
              System.out.println(rows + " User records deleted");

          }  
于 2013-06-18T16:43:30.377 回答