When should I use MySQL transactions?

后端 未结 2 627
逝去的感伤
逝去的感伤 2020-12-18 15:27

I read some articles about when I should use transactions. I read:

When should I use transactions? Basically any time you have a un

2条回答
  •  轮回少年
    2020-12-18 15:57

    You use transactions whenever you need a group of related queries to be executed as if it was only 1 query.

    For example:

    In a shopping cart someone ads a product, you update the store inventory (decrease existences), and updates the customer's cart (Increase products on cart). In this case 2 operations take place, and that's why you create a transaction, if one of the queries fails (insuficient products on the store) the second query should not happen (add product to customer's cart). In this case, the 2 queries conform a unit of work, meaning that the database should process both or none.

    Now, taking into consideration your points, I don't see a solid reason for using transactions to execute unrelated queries (unless there is a special need). Depending on the database engine you are using, and the system you are developing unnecessary transactions will create a performance bottleneck.

    On the other hand, there may be some applications where you may need to perform multiple transactions, but that is something you should decide on a case by case as there is no general rule.

    Regarding your concern of limiting the amount of transactions per page, or create only one transaction per page I can only say that this depends on what you are trying to acomplish. You may may need to perform 10 related queries wich should be rolled back together upon failure then you need one transaction. If you need to run many unrelated queries with no need to roll back means you don't even need a transaction.

    You can also check wikipedia's entry about this subject:

    http://en.wikipedia.org/wiki/Database_transaction

提交回复
热议问题