Skip to Main Content

Java Database Connectivity (JDBC)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

What is the recommended practice for detecting a duplicate?

843859Jun 26 2008 — edited Jan 19 2015
Hi

Although this question is pretty basic, I can not seem to find an existing thread that addresses it fully.

My question is as follows:

What is the recommended way to detect a duplicate record when performing an 'INSERT'?

In my scenario, I have a table of users with a username column that is 'unique'. When a user registers, I need to tell him if the username already exists.

One option, of course, is to perform a 'SELECT' query to check if the username exists, and only then perform the 'INSERT'. However, if 2 users register almost simultaneously, the username might be inserted after the 'SELECT' but before the 'INSERT'.

Another option is to catch the SQL Exception. However, as far as I can see, the exact Exception will be vendor specific. If the code is going to be vendor-neutral, it will be challenging to pin-point if the Exception was caused by a unique constraint.

I'm wondering if there is some sort of recommended strategy for this situation?

Thanks
Pete

PS: I am using standard JDBC - not ORM.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 28 2008
Added on Jun 26 2008
71 comments
241 views