How to make sure there is no race condition in MySQL database when incrementing a field?

前端 未结 2 1790
你的背包
你的背包 2020-11-27 14:16

How to prevent a race condition in MySQL database when two connections want to update the same record?

For example, connection 1 wants to increase \"tries\" counter.

2条回答
  •  孤街浪徒
    2020-11-27 15:02

    Use a single statement instead of two. A single UPDATE statement that performs both the read and the write will be atomic and won't conflict with another simultaneous update.

    UPDATE table SET tries = tries + 1 WHERE ...
    

    Or you can use transactions to make the two operations atomic.

    BEGIN
    SELECT ...
    UPDATE ...
    COMMIT
    

    Or, more primitively, lock the table while you're reading/writing to it.

    LOCK TABLES table WRITE
    SELECT ...
    UPDATE ...
    UNLOCK TABLES
    

提交回复
热议问题