mysql commit and transaction

前端 未结 1 830
天涯浪人
天涯浪人 2021-02-09 01:00

I have a question regarding mysql commits and transactions.

I have a couple of php statements that execute mysql queries.

Do I just say the following?

         


        
1条回答
  •  北荒
    北荒 (楼主)
    2021-02-09 01:39

    In InnoDB, you do not need to explicitly start or end transactions for single queries if you have not changed the default setting of autocommit, which is "on". If autocommit is on, InnoDB automatically encloses every single SQL query in a transaction, which is the equivalent of START TRANSACTION; query; COMMIT;.

    If you explicitly use START TRANSACTION in InnoDB with autocommit on, then any queries executed after a START TRANSACTION statement will either all be executed, or all of them will fail. This is useful in banking environments, for example: if I am transferring $500 to your bank account, that operation should only succeed if the sum has been subtracted from my bank balance and added to yours. So in this case, you'd run something like

    START TRANSACTION;
    UPDATE customers SET balance = balance - 500 WHERE customer = 'Daan';
    UPDATE customers SET balance = balance + 500 WHERE customer = 'Dennis';
    COMMIT;
    

    This ensures that either both queries will run successfully, or none, but not just one. This post has some more on when you should use transactions.

    In InnoDB, you will very rarely have to lock entire tables; InnoDB, unlike MyISAM, supports row-level locking. This means clients do not have to lock the entire table, forcing other clients to wait. Clients should only lock the rows they actually need, allowing other clients to continue accessing the rows they need.

    You can read more about InnoDB transactions here. Your questions about deadlocking are answered in sections 14.2.8.8 and 14.2.8.9 of the docs. If a query fails, your MySQL driver will return an error message indicating the reason; your app should then reissue the queries if required.

    Finally, in your example code, you used mysql_query. If you are writing new code, please stop using the old, slow, and deprecated mysql_ library for PHP and use mysqli_ or PDO instead :)

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