Find if an SQLException was thrown because of a duplicate

前端 未结 9 2610
青春惊慌失措
青春惊慌失措 2021-02-19 11:01

I have a Java program that is agnostic from the database and I need to know, while inserting, if an SQLException was thrown because of a duplicate key.

If I was using a

9条回答
  •  半阙折子戏
    2021-02-19 11:39

    Well, if you can't rely on the exception to tell you why it was thrown, you could test by following the exception with a "select count(*) from table where key = @keyfailedtoinsert;"

    Unfortunately, the exception isn't guaranteed to give you the table name and key name. In some cases, the java code that called called the JDBC driver may never have had them, e.g., if the insert happened wihin a stored procedure, or as in a trigger.

    So you're back to having to trust each JDBC driver's vendor.

提交回复
热议问题