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

前端 未结 2 1782
你的背包
你的背包 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:05

    Here's 3 different approaches:

    Atomic update

    update table set tries=tries+1 where condition=value;
    

    and it will be done atomically.

    Use transactions

    If you do need to first select the value and update it in your application, you likely need to use transactions. That means you'll have to use InnoDB, not MyISAM tables. Your query would be something like:

    BEGIN; //or any method in the API you use that starts a transaction
    select tries from table where condition=value for update;
    .. do application logic to add to `tries`
    update table set tries=newvalue where condition=value;
    END;
    

    if the transaction fails, you might need to manually retry it.

    Version scheme

    A common approach is to introduce a version column in your table. Your queries would do something like:

    select tries,version from table where condition=value;
    .. do application logic, and remember the old version value.
    update table set tries=newvalue,version=version + 1 where condition=value and version=oldversion;
    

    If that update fails/returns 0 rows affected, someone else has updated the table in the mean time. You have to start all over - that is, select the new values, do the application logic and try the update again.

提交回复
热议问题