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

前端 未结 8 469
别跟我提以往
别跟我提以往 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:16

    I would leave that work entirely to the database; your code should focus on catching and properly handling the exception.

    Reasons:

    1. Performance- The database will be highly optimized to enforce constraints in a fast and efficient way. You won't have time to optimize your code as well.
    2. Maintainability- If the constraints change in the future, you won't have to modify your code, or perhaps you will just have to add a new catch{}. If a constraint is dropped, you won't have to touch your code at all.

提交回复
热议问题