views:

31

answers:

2

I am working on a web application, and at a point where I submit forms that are unique to the user, a

 MySQLIntegrityConstraintViolationException Duplicate entry -'username' 
for key 'PRIMARY'

I am well aware of why this is being thrown, because I am attempting to enter a duplicate entry into the database with the same primary key. I would appreciate no comments on this, as it might be a redundant.

What I am really asking is how should I handle this. I have attempted to catch this exception, but apparently my lack of experience has caught up to me.

I would appreciate your help with it.

Is there a better method for checking for duplicate entries in a database?

For example, should I do what I do when checking for duplicate members, and just do a check to the database for a matching username and password?

Thanks

+2  A: 

Yes, especially in this scenario it is better to check whether another user exists with the same username before trying to insert the user.

Bozho
+1  A: 

Generally, if it's possible avoid throwing Exceptions since they are a heavy mechanism for controlling program workflow. You should only use them to trace bugs and irregular activities/situations. All that means that if you catch an exception, the only thing you can do is log some more, wrap the exception in another exception and eventually triggering some fall-back program logic.

Don't expect to catch exceptions and just check for correct user name. I suppose you will be doing this check a lot if you are developing some sort of registration form ... there are a few popular words for common users and if you implement it with exceptions, you will catch it pretty often...

Unfortunately, if your database is very large, the primary keys are many and complex objects , than you can't afford to keep some of the elements in memory to perform this check for duplicate entries.

Leni Kirilov