Find if an SQLException was thrown because of a duplicate

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

    You could "train" the program on startup (or config) by inserting a known duplicate key, and recording the thrown error code.

    0 讨论(0)
  • 2021-02-19 11:46

    If you are using spring, set your unique KEY name as UK_user_id for example and catch the DataIntegrityViolationException.
    You can then compare ex.getCause().getConstraintName() with UK_user_id.

    0 讨论(0)
  • 2021-02-19 11:46

    I'm assuming you aren't using JDBC or this would be a very simple error lookup.

    Do you have a different set of classes for accessing the different databases? If so, you could catch the exception in the database specific classes and throw your own exception type that is shared among all the database types.

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