Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an SQLException was thrown because of a duplicate

I have a Java program that is agnostic from the database and I need to know, while inserting, if an SQLException was thrown because of a duplicate key.

If I was using a single database driver I would simply use the ErrorCode, but since I can be using very different engines the ErrorCode are not the same.

Has anyone done this before? Any ideas?

Many TIA!

Edit: I have a configuration file where I store the driver class (ie: org.apache.derby.jdbc.ClientDriver) and some other needed information (ie: username, password, url...). The connection is always passed as a "java.SQL.Connection" so I don't really care what drivers is being used.

like image 742
ferro Avatar asked Apr 07 '09 17:04

ferro


1 Answers

This is exactly what SQLException.getSQLState() is for. Acoording to Google, "23000" indicates a unique constraint violation in at least MySQL, PostgreSQL, and Oracle.

like image 193
Matt Solnit Avatar answered Oct 06 '22 09:10

Matt Solnit