作者:mobiledu2502885243 | 来源:互联网 | 2022-12-16 07:58
在MySQL文档中有一个我不理解的声明:
将LOCK TABLES和UNLOCK TABLES与事务表(如InnoDB表)一起使用的正确方法是使用SET autocommit = 0(不是START TRANSACTION)后跟LOCK TABLES 开始事务,并且在提交事务之前不调用UNLOCK TABLES明确.(https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html)
即使在文档中搜索了很多并研究了"autocommit"和"START TRANSACTION"的描述之后,我真的不明白为什么要使用autocommit而不是START TRANSACTION.有任何想法吗?谢谢
1> Bill Karwin..:
LOCK TABLES
隐式提交事务,根据https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
因此,如果您按照以下顺序执行操作,则不会执行您的操作:
BEGIN;
/* I think I'm in transaction 1 */
LOCK TABLES ...;
/* but that implicitly committed transaction 1 */
UPDATE blab blah ...;
/* I think I'm still in transaction 1, but this update caused
a new transaction 2 to begin and autocommit */
UPDATE yadda yadda ...;
/* I think I'm still in transaction 1, but this update caused
a new transaction 3 to begin and autocommit */
COMMIT;
使用事务的关键是当您需要运行多个更新时,但您希望所有更新的结果一起提交或根本不提交.
上面的示例不会以原子方式将两个更新一起提交.他们每个人都有自己的自动交易.因此,一个人可能会成功但另一个人则不会.
建议是执行以下操作:
SET autocommit=0;
LOCK TABLES ...;
/* that implicitly committed any outstanding transaction, but that's OK */
UPDATE blab blah ...;
/* because autocommit=0, a new DML statement implicitly starts a new transaction */
UPDATE yadda yadda ...;
/* the new transaction is still open */
COMMIT;
UNLOCK TABLES;
这会以原子方式将两个更新一起提交.
为什么不只是LOCK TABLES然后BEGIN开始交易?
https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html说:
开始事务(例如,使用START TRANSACTION)隐式提交任何当前事务并释放现有表锁.
这对我来说似乎很奇怪.显式BEGIN(或START TRANSACTION)释放表锁,但事务的隐式启动不会?在我看来,这个功能充满了WTF.但这就是记录的内容.