javamysqltry-catchsql-insertmysql-error-1062

Catch duplicate key insert exception


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?


Solution

  • 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.