Java + MySQL integrity violation handling

后端 未结 3 1155
日久生厌
日久生厌 2021-01-06 03:14

I write Java program using JDBC (mysql database). When I violate mysql integrity (f.e. I try to insert same primary key value) I catch SQL exception. Should

3条回答
  •  抹茶落季
    2021-01-06 04:17

    As others have mentioned that there are two possible approaches, one is to test and then insert/update otherwise handle SQL Exception. Both these approaches have their downsides:

    • Caveat for "Test before inserting" is that every transaction will have additional queries which will impact performance. This is specially a bigger issue when such erroneous transactions are few in number.
    • Caveat for "Evaluating SQL Exception" is that such exception messages are very database specific. These messages, most of the time, don't give specific information beyond stating that there is constrain violation.

    So, I will propose an approach which is hybrid of the two.

    • Don't perform the test before insert.
    • Let database throw an exception.
    • Catch SQL Exception.
    • In the exception flow (catch block), do additional queries to form very specific error messages to indicate customers what has exactly failed (unique key, primary key, foreign key, specific columns etc).

    This may require few additional lines of code but it definitely improves performance and generates friendly error messages.

提交回复
热议问题