Find if an SQLException was thrown because of a duplicate

前端 未结 9 2591
青春惊慌失措
青春惊慌失措 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:26

    With basic JDBC, there really isn't a way to do what you are saying in a cross-database manner. As you mentioned getErrorCode could be used, but required vendor-specific error codes.

    The only three ways I see to get around this is:

    1. Use some sort of framework that does all of the translating from error code to meaningful exceptions (Hibernate would probably do this, someone else mentioned that Spring does)
    2. Check for the duplicate manually (with a select) prior to doing your insert. (This wouldn't be 100%, as its technically possible that someone could have done an insert after your query).
    3. After you get any sql exception on the insert, try to query for that id. If you can actually find the match - you can be fairly sure that the error you received was due to a duplicate primary key. (Although its possible that there was multiple problems, and that wasn't actually the one that was thrown).

    My recommendation would be to write your code to avoid the problem as much as possible, and then (if absolutely necessary), use #3.

提交回复
热议问题