views:

606

answers:

3

Hi All, I want to know whether is it a good idea to catch exception based on unique index of sql in java.

i want to catch an exception like 'duplicate entry for 1-0' if so then handle exception otherwise insert properly in database table?

+1  A: 

I don't see why not. It's probably more efficient than running a query before the insert. It's probably better to catch the exception's error code rather than recognising the error message, though.

skaffman
Also, if you happen to be using Spring, then the JDBC xception Translator will translate the SQLException into a DataIntegrityViolationException. It might be nicer to catch that instead of the raw exception.
skaffman
+1  A: 

You could use the REPLACE command. It inserts/updates based on the existence of the record. And its atomic too whereas query then insert/update is not. It depends on what do you want to do if you detect the key violation?

kd304
+2  A: 

I say you don't do that, for two reasons:

  • the error messages are a bit unclear: ERROR 1062 (23000): Duplicate entry 'xxx' for key 1. Are you always 100% sure which key is 1?
  • it locks in you to a specific database vendor

I find it simpler to transactionally:

  • check for row's existence;
  • throw an exception if the row already exists;
  • insert the new row.


Performance issues:

I say measure twice, cut once. Profile the usage for your specific use case. Top of my head I would say that the performance will not be an issue except for the heavy db usage scenarios.

The reason is that once you perform a SELECT over that specific row, its data will be placed in the database caches and immediately used for insertion check done on the index for the INSERT statement. Also keeping in mind that this access is backed by an index leads to the conclusion that performance will not be an issue.

But, as always, do measure.

Robert Munteanu
I agree with you Robert. well but will it not affect the performance as everytime though the record does not exists it has to check and then insert. Also on the other side as skaffman said it will be easy to catch the exception as i dont know java can anyone explain to me that will that be easy way of catching exception, as may be the more indexing will reduce the performace.
MySQL DBA
Please see my update.
Robert Munteanu
Thanks for your input.
MySQL DBA