我正在研究 MySQLi 的回滚管理,我很好奇 begin_transaction()
方法有什么好处。我看到的许多示例通过关闭自动提交来完全跳过它,然后执行一些返回成功值的查询,并根据返回值测试复合 bool 值以提交或回滚多个语句。
在我们希望根据所有查询的成功提交或回滚一组查询的情况下,begin_transaction()
方法似乎实际上没有做任何有用的工作。我可以看到它可能通过显式声明事务来增加代码的可读性,但是 begin_transaction()
除了可读性之外还有其他值(value)吗?它有什么实际作用?
最佳答案
正如在其他答案中已经提到的,begin_transaction()
启动一个事务,而不影响 autocommit
的值。在调用 commit()
或触发 implicit commit 之前,查询不会提交到数据库中。 .
如 MySQL 文档中所述:
A session that has autocommit enabled can perform a multiple-statement transaction by starting it with an explicit START TRANSACTION or BEGIN statement and ending it with a COMMIT or ROLLBACK statement. See Section 13.3.1, “START TRANSACTION, COMMIT, and ROLLBACK Statements”.
If autocommit mode is disabled within a session with SET autocommit = 0, the session always has a transaction open. A COMMIT or ROLLBACK statement ends the current transaction and a new one starts.
这意味着 begin_transaction()
和 autocommit(FALSE);
之间的主要区别是您想要一次性事务还是连续事务。
使用 begin_transaction()
的简单一次性交易如下所示:
<?php
// Switch on error reporting with exception mode
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'db_name');
$mysqli->set_charset('utf8mb4');
try {
// Start transaction
$mysqli->begin_transaction();
$mysqli->query('INSERT INTO some_table(col2) VALUE(4)');
$mysqli->query('INSERT INTO some_table(col2) VALUE(4');
// Commit changes
$mysqli->commit();
} catch (\Throwable $e) {
// Something went wrong. Rollback
$mysqli->rollback();
throw $e;
}
这种方法比完全关闭自动提交模式更清晰。 .
关于php - 在 MySQLi 中使用 "begin_transaction"方法有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48812724/