Detecting Duplicate Keys

JIA Java Italian Association

A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

Joe Sam Shirah adds: You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000. For more information, see Where can I find a list of the possible SQLStates returned by SQLException.getSQLState()? and my JDBC 2.0 Fundamentals Short Course at the Java Developer Connection.