Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top