Java 捕获重复键插入异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26761436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:13:38  来源:igfitidea点击:

Catch duplicate key insert exception

javamysqltry-catch

提问by Josh

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

我有一个带有唯一主键列的表,称为id. 有时,当我执行INSERT查询时,我会收到错误消息,因为该id值已被使用。

Can I catch this specific error with tryand catch?

我可以用try和来捕捉这个特定的错误catch吗?

采纳答案by Daniel

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

看起来 mysql 正在为重复的主键抛出 1062 错误代码。您可以检查 sql 异常的错误代码:

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.

请注意,这种方法不是跨数据库供应商的,因为不同的供应商可能对重复的 PK 有不同的错误代码。