Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 667
Josh Avatar asked Nov 05 '14 15:11

Josh


1 Answers

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.

like image 137
Daniel Avatar answered Oct 07 '22 19:10

Daniel