This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes Unique datatype in database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Unique datatype in database" Watch "Unique datatype in database" New topic
Author

Unique datatype in database

malik ge
Ranch Hand

Joined: May 13, 2011
Posts: 69
Hi,
I have a database in which I have make the userName field unique. So that only one userName exist in the database.
Now if user enters his information then How I can check that if the username already exists in the database?
Should I have to do:
and then compare the user Names with each other?
Or is there any other way to do this.
Thanks in advance...
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

No, your query would be

and you would test to see if that query returned any records or not.

Don't be tempted to use string concatenation to create that query, though. Use a PreparedStatement and plug in the user ID via a parameter.
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3703
    
    5

Also, if you want to avoid case-insensitive differences, you might consider "lower(userID) = lower(?)". Granted, some databases can be configured to always perform case insensitive matching.

One issue with unique usernames is that even if you check ahead of time, a race condition could have two users creating the same record at the same time. It doesn't mean you shouldn't check ahead of time, you should always avoid throwing exceptions if they can be solved through application logic, but you should always have a pathway that handles when the database throws a uniqueness violation even after checking ahead of time.


My Blog: Down Home Country Coding with Scott Selikoff
 
Consider Paul's rocket mass heater.
 
subject: Unique datatype in database
 
Similar Threads
related to pdf
Mail Server - Database Design
dont understand implementation sessions
MySQL - add and remove username from table
Case Insensitive Hibernate Queries