11

I have a table with a unique primary key column called id. Sometimes when I perform an INSERT query I get an error because the id value is already used.

Can I catch this specific error with try and catch?

AdamMc331
  • 16,492
  • 10
  • 71
  • 133
Josh
  • 227
  • 1
  • 4
  • 8

1 Answers1

15

Looks like mysql is throwing 1062 error code for duplicate primary key. You can check the error code for your sql exception :

public static final int MYSQL_DUPLICATE_PK = 1062;

try{
    //code that throws sql exception
} catch(SQLException e){
    if(e.getErrorCode() == MYSQL_DUPLICATE_PK ){
        //duplicate primary key 
    }
}

Notice that this approach is not cross database vendor, because different vendors might have different error codes for duplicate PK.

Daniel
  • 1,861
  • 1
  • 15
  • 23
  • I thought `SqlException` was the class but wasn't sure. Great idea on checking for specific error code - I had no idea that was possible. – AdamMc331 Nov 05 '14 at 16:05
  • 2
    For completeness - Under Oracle I believe the error code returned is `1` [see here](http://www.dba-oracle.com/sf_ora_00001_unique_constraint_violated.htm). – OldCurmudgeon Nov 05 '14 at 16:07