Validation of repetition of name in sql DB?
What's happening in the backend of the if(rs.next())
:
- When your code execution reaches the
if()
, it executes thers.next()
. - Depending on the result of your query, the ResultSet object
rs
either has zero or more results. - 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. - E.g. if there are three records in the
rs
object, say [0,1,2], then initially the pointer points to -1. - Every time you call
next()
onrs
, the pointer is moved one place forward and if there is a record present on the new location,next()
returnstrue
. - If there is no record present on the new location,
next()
returnsfalse
. - For the sake of your question, assume that there is a record
available, and
rs.next()
returnstrue
. - Hence, the execution enters inside the
if()
body. -
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 theif()
body then. - Here, the compiler executes the code that you have written i.e. setting the
nameTextField
's text tonull
and showing a pop-up with your error message. - 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). - But the code execution doesn't stop here, and this is where things seem to get fishy in your code.
- In the code you have provided with this question, you do not have any
return
orthrow
orbreak
before yourif()
body ends. - 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!