Validation of repetition of name in sql DB?

What's happening in the backend of the if(rs.next()):

  1. When your code execution reaches the if(), it executes the rs.next().
  2. Depending on the result of your query, the ResultSet object rs either has zero or more results.
  3. The rs object maintains a pointer to all the records it contains. Initially, this pointer points to a sort of "dummy" location before the actual record.
  4. E.g. if there are three records in the rs object, say [0,1,2], then initially the pointer points to -1.
  5. Every time you call next() on rs, the pointer is moved one place forward and if there is a record present on the new location, next() returns true.
  6. If there is no record present on the new location, next() returns false.
  7. For the sake of your question, assume that there is a record available, and rs.next() returns true.
  8. Hence, the execution enters inside the if() body.
  9. rs.next() is usually called inside a loop if more than one record is expected from a select query, but since there's no loop in your code, rs.next() executes only once. That's it, there isn't anything else happening with it. On to the if() body then.
  10. Here, the compiler executes the code that you have written i.e. setting the nameTextField's text to null and showing a pop-up with your error message.
  11. Then, the compiler waits for the error dialog to be closed (I think, not sure about this step as it's been too long, but go look at the javadocs to see whether JOptionPane.showMessageDialog() is non-blocking or blocking).
  12. But the code execution doesn't stop here, and this is where things seem to get fishy in your code.
  13. In the code you have provided with this question, you do not have any return or throw or break before your if() body ends.
  14. So what the compiler does is it simply exits the if() body and continues executing whatever code comes below - which I am assuming is for inserting data, and that's where your "Data has been inserted" pop-up is coming from.

Adding a return statement or throwing an Exception just below JOptionPane.showMessageDialog(), inside the if(rs.next()) should solve your problem, assuming my assumption regarding the missing code is correct.

Ciao!