简体   繁体   English

在PHP中,如果我在没有提交的情况下断开连接而不是提交它,我可以让MySQL回滚一个事务吗?

[英]In PHP, can I get MySQL to rollback a transaction if I disconnect without committing, rather than commit it?

If I run the following PHP, I would expect no value to be inserted into the test table, because I have a transaction that I haven't committed: 如果我运行以下PHP,我希望没有值插入到测试表中,因为我有一个我没有提交的事务:

$db = mysql_connect("localhost","test","test");
mysql_select_db("test");
mysql_query("begin transaction;");
mysql_query("insert into Test values (1);") or die("insert error: ". mysql_errror());
die('Data should not be commited\n');
mysql_query("commit;"); // never occurs because of the die()

But instead it seems to commit anyway. 但反正似乎无论如何都要承诺。 Is there a way to turn off this behaviour without turning off autocommit for the PHP that doesn't use transactions elsewhere on the site? 有没有办法关闭此行为而不关闭不使用网站上其他地方的交易的PHP的自动提交?

Edit: This was just a stupid typo. 编辑:这只是一个愚蠢的错字。 It should be "start transaction" or "begin". 它应该是“开始交易”或“开始”。 Not "begin transaction". 不是“开始交易”。 Sorry to waste peoples time. 抱歉浪费时间。

Use mysql_query('BEGIN'). 使用mysql_query('BEGIN')。 The SQL "BEGIN TRANSACTION" is not valid (and in fact mysql_query is returning false on that query, which means there is an error). SQL“BEGIN TRANSACTION”无效(事实上,mysql_query在该查询中返回false,这意味着存在错误)。 It's not working because you never start a transaction. 它没有用,因为你从未开始交易。

The syntax to start a transaction is: 启动事务的语法是:

START TRANSACTION

The feature you are talking about is AUTOCOMMIT. 您正在谈论的功能 AUTOCOMMIT。 If you don't want it, you'll have to disable it: 如果你不想要它,你将不得不禁用它:

SET autocommit = 0

The reference can be found at http://dev.mysql.com/doc/refman/5.1/en/commit.html 该参考资料可以在http://dev.mysql.com/doc/refman/5.1/en/commit.html找到

I also recommend that you test the return value of all mysql_...() functions. 我还建议您测试所有mysql _...()函数的返回值。 You cannot assume that they'll always run successfully. 你不能假设他们总能成功运行。

By default, the transaction will not be rolled back. 默认情况下,不会回滚事务。 It is the responsibility of your application code to decide how to handle this error, whether that's trying again, or rolling back. 应用程序代码负责决定如何处理此错误,无论是再次尝试还是回滚。

If you want automatic rollback, that is also explained in the manual: 如果您想要自动回滚,也可以在手册中进行说明:

The current transaction is not rolled back. To have the entire transaction roll back, start the server with the `--innodb_rollback_on_timeout` option.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM