如果未达到 COMMIT TRANSACTION,则自动回滚
考虑以下事项:
START TRANSACTION;
BEGIN;
INSERT INTO prp_property1 (module_name,environment_name,NAME,VALUE) VALUES ('','production','','300000');
/** Assume there is syntax error SQL here...**/
Blah blah blah
DELETE FROM prp_property1 WHERE environment_name = 'production';
COMMIT TRANSACTION;
问题:
我注意到事务自动回滚并且记录插入尝试失败.
I noticed that the transaction automatically rolls back and the record insert attempt fails.
如果我不提供错误处理程序或错误检查以及 ROLLBACK TRANSACTION
如上所述,它是否安全,因为它似乎在上面的示例中完成了工作,因为 COMMIT TRANSACTION
永远不会被执行?
If I don't provide a error handler or error check along with ROLLBACK TRANSACTION
as above, is it safe as it seems to be doing the job in an example like above because the COMMIT TRANSACTION
never gets executed?
我假设事务会立即回滚并在发生错误时立即丢弃.
I assume the transaction is rolled back immediately and discarded as soon as a error occurs.
推荐答案
否,事务不会在发生错误时立即回滚.但是您可能正在使用应用此策略的客户端应用程序.
No, transactions are not rolled back as soon as an error occurs. But you may be using a client-application which applies this policy.
例如,如果您使用的是 mysql 命令行客户端,那么它通常会在发生错误时停止执行并退出.在事务进行时退出确实会导致它回滚.
For example, if you are using the mysql command-line client, then it normally stops executing when an error occurs and will quit. Quitting while a transaction is in progress does cause it to be rolled back.
在编写自己的应用程序时,可以控制回滚策略,但有一些例外:
When you are writing your own application, you can control the policy on rollback, but there are some exceptions:
- 退出(即与数据库断开连接)总是回滚正在进行的事务
- 死锁或锁等待超时隐式导致回滚
除了这些条件之外,如果您调用一个产生错误的命令,错误会正常返回,您可以随意做任何想做的事情,包括提交事务.
Other than these conditions, if you invoke a command which generates an error, the error is returned as normal, and you are free to do whatever you like, including committing the transaction anyway.
相关文章