Catching certain FK exception with Jdbc
I am using Jdbc. When a foreign key constraint is broken, a MySQLIntegrityConstraintViolationException is thrown.
Right now I just do some pre-checking before doing inserts to prevent this. But I was thinking.. would it be more efficient to just try to do the insert straight away and then catch the exception? What do you think of this?
For 开发者_如何学Pythonthis to be possible, I would need to be able to check why the MySQLIntegrityConstraintViolationException was thrown after catching it. Eg, I may need to know which FK constraint failed. Can this be done?
But I was thinking.. would it be more efficient to just try to do the insert straight away and then catch the exception?
If exceptions happen rarely (usually the case), this is indeed a more efficient and much more simple way.
If the chance of getting FK violation is high, than the pre-insert checks (providing they do not hit the database) will save the round-trip to db and back, and thus will be more efficient.
Re: figuring out the reason of failure. Vendor exceptions usually contain some information about what constraint has triggered the exception. You should look at vendor exception's fields and methods.
精彩评论