Delete from DB in Java

I want to delete a row in DB and it works but here is the problem:

  • If I enter the value that exists in DB, it is deleted and I get a message “Your Booking is successful canceled”

  • But also if I enter the value that not exists in DB, I get the same message. Why if the condition does not work?

      String sql = "delete from vaccines.patients where idNum = ?";
      String res = "Your Booking is successfully canceled";
      PreparedStatement state;
    
      try {
          state = con.prepareStatement(sql);
          state.setString(1, member.getIdNum());
          if (member.getIdNum().equals(null)) {
              res = "Enter id";
          }
    
          state.executeUpdate();
      } catch (SQLException e) {
          e.printStackTrace();
          res="Your Booking is not successfully canceled";
      }
    

Answer

You must check the number of affected rows instead since an update statement not affecting any rows won’t error out.

e.g.

int rowCount = state.executeUpdate();

if (rowCount == 0) {
    throw ...;
}