当前位置: 首页 > 知识库问答 >
问题:

捕获重复条目异常

洪开济
2023-03-14

如何捕获此异常:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
                                      Duplicate entry '22-85' for key 'ID_CONTACT'

共有3个答案

寿子轩
2023-03-14

vendorCode2601用于unique index constraint违犯,因此您可以通过e.getErrorCode()==2601检查SQLException cewndorCode。示例代码

try {
    ao_history_repository.save(new AoHistory(..));
} catch (SQLException e) {
    if (e.getErrorCode() == 2601) {
        System.out.println("handle duplicate index error here!");
    } else {
        System.out.println("handle other error code here!");
    }
}
燕经国
2023-03-14

如果您使用的是Java1.6,请注意

例如

try {
    ps.executeUpdate("INSERT INTO ...");
} catch (SQLIntegrityConstraintViolationException e) {
    // Duplicate entry
} catch (SQLException e) {
    // Other SQL Exception
}

或者

try {
    ps.executeUpdate("INSERT INTO ...");
} catch (SQLException e) {
    if (e instanceof SQLIntegrityConstraintViolationException) {
        // Duplicate entry
    } else {
        // Other SQL Exception
    }
}
越开畅
2023-03-14

我使用spring,所以我们通过org.springframework.dao.DataIntegrityViolationException

try {
    ao_history_repository.save(new AoHistory(..));
} catch (DataIntegrityViolationException e) {
    System.out.println("history already exist");
}

但正如@KevinGuancheDarias提到的:

请注意,虽然这工作。我建议通过在保存之前发布findBy来解决这个问题,因为这是混乱的,我认为它不保证在未来的版本中工作,甚至可能在没有通知的情况下中断。

 类似资料:
  • 问题内容: 我如何捕获此异常: 问题答案: 我用弹簧,所以我们通过 但是就像@KevinGuancheDarias提到的那样: 请注意,虽然这可行。 我建议通过在save之前发出findBy来解决该问题 ,因为这很麻烦,我认为不保证它将在将来的版本中使用,甚至可能在没有通知的情况下中断。

  • 无法在中包装流对象。 我试过这样: Eclipse开始抱怨在下划线,并建议它需要用try/catch包围

  • 我的数据库中有这些(简化的)表 我已经用这两个(简化的)类映射了表 公司 如果我注释第26、28、30和32行(上面标记的),同样的代码可以完美地工作。但我想知道为什么会产生异常。为什么是复制的钥匙? 提前谢了。

  • 问题内容: 我有一个带有唯一主键列的表。有时,当我执行查询时会收到错误消息,因为该值已被使用。 我可以使用和捕获此特定错误吗? 问题答案: 看起来mysql为重复的主键抛出了1062错误代码。您可以检查sql异常的错误代码: 注意,这种方法不是跨数据库供应商的,因为不同的供应商对于重复的PK可能具有不同的错误代码。

  • 有可能在SWIFT中捕捉异常吗?给定以下代码: 有可能防止异常使整个程序崩溃吗?也就是说,在Objective-C中,与以下内容相对应的Swift等价是什么: