Should I check for DB constraints in code or should I catch exceptions thrown by DB

前端 未结 8 459
别跟我提以往
别跟我提以往 2021-02-04 03:43

I have an application that saves data into a table called Jobs. The Jobs table has a column called Name which has a UNIQUE constraint. The Name column is not PRIMARY KEY. I wond

相关标签:
8条回答
  • 2021-02-04 04:18

    Personally I'd catch the exception. It's much simpler and requires much less code.

    0 讨论(0)
  • 2021-02-04 04:22

    You should definitely check for any exception thrown by the data access layer. The problem with checking if there is a record with the same value is, that it requires you to lock the table for modifications until you insert the new record to prevent race conditions.

    It is generally advisable to check for exceptions/errors, even if you have checked everything yourself before. There is almost always something that can go wrong or which you haven't considered in your code but is enforced by the database.

    Edit: If I understand the question right, it is not about if the constraint should be enforced by the database or not, but how to deal with it in the application code. Of course you should always set up all constraints in the database to prevent bad data entering your database.

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