Catch duplicate key insert exception

前端 未结 1 1696
时光说笑
时光说笑 2021-01-04 10:23

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 valu

相关标签:
1条回答
  • 2021-01-04 10:51

    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.

    0 讨论(0)
提交回复
热议问题