在事务中设置 autocommit=0 有什么作用吗?

Does setting autocommit=0 within a transaction do anything?

我正在审查另一位开发人员的代码。他有一个在 MySQL 事务开始时显式添加 set autocommit=0 的提交。这会导致会话中其他非事务性查询出现问题。

在交易中添加 set autocommit=0 交易有什么影响吗?我认为它不会,因为交易无论如何都会隐式地这样做。

[我能为这次提交想出的唯一理由可能是数据库曾经使用过 MyISAM(相对于当前的 InnoDB),这可能是模仿前者事务的一种方式?]

如果事务处于活动状态,则不受 SET autocommit = 0 的影响。

否则,如果 autocommit 的前值是 1SET autocommit = 0 开始新的交易。

如果您正在使用 MariaDB 并且有疑问,您可以检查 in_transaction 变量。

来自MySQL Reference

After disabling autocommit mode by setting the autocommit variable to zero, changes to transaction-safe tables (such as those for InnoDB or NDB) are not made permanent immediately. You must use COMMIT to store your changes to disk or ROLLBACK to ignore the changes.

设置autocommit=0将修改整个会话。 事务和非事务命令需要显式提交才能影响数据库。