php - 在 MySQLi 中使用 "begin_transaction"方法有什么好处?

标签 php mysqli transactions

我正在研究 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/

相关文章:

php - GhostScript PDF 合并(丢失可编辑字段)

php - 如何将动态值存入数据库

php - 使用 mysqli 计算行数并传递信息

php - 事务回滚后怎么办

java - 从 php exec 或 shell_exec 运行 java jar 不适用于蜡染

php - 将用户数据从 PHP 同步到 meteor 应用程序

PHP MySQLI 选择多列返回 null

php - 将阿拉伯语数据插入mysql数据库

svn - 如何检索 svn 事务 ID

php - PHP PDO 的事务究竟如何与并发一起工作?