mysqli_commit故障会自动回滚吗?

我对PHP手册中的代码如何运行有一些疑问.我看到了其他引发异常(通常是面向对象的代码)或使用标志来跟踪每个查询失败的示例.

我的问题是,为什么在决定提交或回滚之前,您必须标记错误并测试该标记.查看下面的示例,看来如果提交不起作用,则无论如何都不会提交任何查询.

我还注意到它们只是在提交失败时退出.这会自动回滚所有内容吗?

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F',     11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Sw*', 'F', 9.4)");

/* commit transaction */
if (!mysqli_commit($link)) {
    print("Transaction commit failed\n");
    exit();
}

/* close connection */
mysqli_close($link);
?>

解决方法:

Looking at the example below it appears that if the commit does not work, none of the queries would be committed anyway.

对.

但要点是,不仅提交会发生错误.但是-更有可能-执行其中一个查询.因此,您不仅需要检查提交结果,还需要检查每个查询的结果并中止整个操作.

因此,您的问题应读为

Does a mysqli failure automatically rollback?

答案是“是,不是”.
默认情况下不会.
但是,如果您因查询失败而中止脚本,则链接将关闭,并且事务将自动回滚.下面的代码将mysql错误转换为PHP致命错误,如果其中一个查询失败,它将自动回滚.

<?php
/* set the proper error reporting mode */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

/* Run your queries */
mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F',     11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Sw*', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* this is the last line, NO other code is needed */
上一篇:php-调用未定义的方法Closure :: query()


下一篇:SQL 增加删除库表