Reputation: 321
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?
Upvotes: 1
Views: 2000
Reputation: 159754
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");
}
Upvotes: 4
Reputation: 7630
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.
.
Upvotes: 1
Reputation: 68715
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");
}
Upvotes: 1