简体   繁体   中英

Deleting an existing user from a database JDBC Oracle

I have a working code here that removes users from a database when you call the removeUser method. :

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()); }
    }

However, I need to make sure the user exists before I delete him, otherwise print that the user does not exist. How can this be accomplished?

You could instead use the result of pstmnt.executeUpdate() to determine if the SQL DELETE operation was successful:

int rowsUpdated = pstmnt.executeUpdate();
if (rowsUpdated == 0) {
    System.out.println("User does not exist");
} else {
    System.out.println("User deleted");
}

pstmnt.executeUpdate() returns row count. which says how many rows are deleted!!

Thus if it's value zero then show message user does not exist. .

Calling executeUpdate will return the number of rows that were modified by the call. Do something like this:

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

          }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM