Java – find out if sqlexception is raised due to repetition
I have a java program that is not related to the database. If sqlexception is thrown due to duplicate keys, I need to know when to insert
If I use a single database driver, I will simply use errorcode, but because I can use very different engines, errorcode is different
Has anyone done it before? Any ideas?
A lot of TIA!
Edit: I have a configuration file that stores the driver class (i.e. org. Apache. Derby. JDBC. Clientdriver) and some other required information (i.e. user name, password, URL...) The connection is always passed as "Java. SQL. Connection", so I don't care what driver is used
Solution
Using basic JDBC, there is no way to do what you say in a cross database way As you mentioned, you can use geterrorcode, but you need a vendor specific error code
The only three methods I see are:
>Use a framework to translate all errors from error code into meaningful exceptions (hibernate may do this, someone mentioned spring) > manually check the copy (with selection) before insertion (this will not be 100%, because technically someone may insert after your query). > After receiving any SQL exception after insertion, try to query the ID. if you can find a match, you can determine that the error you receive is due to the duplicate primary key Although there may be several problems, they are not actually thrown out
My advice is to write your code to avoid this problem as much as possible, and then (if absolutely necessary), use #3