How to properly avoid Mysql Race Conditions

前端 未结 3 623
既然无缘
既然无缘 2021-01-06 02:53

I know this has been asked before, but I\'m still confused and would like to avoid any problems before I go into programming if possible.

I plan on having an interna

相关标签:
3条回答
  • 2021-01-06 03:19

    You may consider Transactions

    BEGING TRANSACTION;
    SELECT ownership FROM ....; 
    UPDATE table .....; // set the ownership if the table not owned yet
    COMMIT;
    

    and also you can ROLLBACK all the queries between the transaction if you caught an error !

    0 讨论(0)
  • 2021-01-06 03:39

    When you post a row, set the column to NULL, not 0.

    Then when a user updates the row to make it their own, update it as follows:

    UPDATE MyTable SET ownership = COALESCE(ownership, $my_user_id) WHERE id = ...
    

    COALESCE() returns its first non-null argument. So even if you and I are updating concurrently, the first one to commit gets to set the value. The second one will not override that value.

    0 讨论(0)
  • 2021-01-06 03:40

    To achieve this, you will need to lock the record somehow. Add a column LockedBy defaulting to 0.

    When someone pushes the button execute a query resembling this:

    UPDATE table SET LockedBy= WHERE LockedBy=0 and id=;

    After the update verify the affected rows (in php mysql_affected_rows). If the value is 0 it means the query did not update anything because the LockedBy column is not 0 and thus locked by someone else.

    Hope this helps

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