Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unique datatype in database

 
malik ge
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Saloon Keeper
Posts: 4014
18
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic