使用 BEGIN 和 START TRANSACTION 时 MySQL AUTOCOMMIT 状态

标签 mysql transactions autocommit

我需要在我的 MySQL 项目中使用事务。但我不确定是否必须使用 mysql_query("SET AUTOCOMMIT=0"); 或不。
我知道我有 2 个选择:

  1. 开始
  2. 开始交易

我还听说这两项中的一项不需要使用 AUTOCOMMIT = 0
请帮助我知道什么时候我必须使用 AUTOCOMMIT = 0 实际使用 BEGINSTART TRANSACTION

谢谢。

最佳答案

the manual 中所述:

By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. The change cannot be rolled back.

To disable autocommit mode implicitly for a single series of statements, use the START TRANSACTION statement:

START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;

With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. The autocommit mode then reverts to its previous state.

手册接着说:

To disable autocommit mode explicitly, use the following statement:

SET autocommit=0;

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

autocommit is a session variable and must be set for each session. To disable autocommit mode for each new connection, see the description of the autocommit system variable at Section 5.1.3, “Server System Variables”.

BEGIN and BEGIN WORK are supported as aliases of START TRANSACTION for initiating a transaction. START TRANSACTION is standard SQL syntax and is the recommended way to start an ad-hoc transaction.

关于使用 BEGIN 和 START TRANSACTION 时 MySQL AUTOCOMMIT 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375890/

相关文章:

java - 防止 JBoss 7 (Jeeves DBMS) 上 JNDI 数据源的 Oracle 连接自动提交

java - 大对象不能在自动提交模式下使用

java - mysql jdbc 不成功回滚

java - 当 Jackrabbit 是全局交易的一部分时,我该如何使用它?

c# - 为空时创建新 SqlConnection 的最佳方法

php - 当日期相同时从 MySQL 获取下一个和上一个

mysql - 尝试将 ID(使用 SET IDENTITY_INSERT)插入表时,phpMyAdmin 给出错误 #1064

java - 无法让Spring事务回滚(java+mysql)

c# - 如何将sql查询存储在变量中

MySQL 连接两个表的帮助