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?
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?
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?
I say you don't do that, for two reasons:
I find it simpler to transactionally:
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.