简体   繁体   English

交易与例外

[英]Transactions and Exceptions

I thought I would ask because I am unsure of the result of this operation not having worked with transactions much in a raw nature. 我想问一下,因为我不确定此操作的结果是否与原始交易无关。

When an exception is thrown in PHP that stops execution, how is a DB transaction handled. 当PHP中引发异常而停止执行时,如何处理数据库事务。 Does it automatically rollback since the connection to the database is dropped from PHP or will a lock remain in place? 因为从PHP断开与数据库的连接,它会自动回滚还是将锁保留在原处?

Pseudo Code 伪码

TX Begin
Select Balance
Logic in PHP
  Exception 
  Rollback
Commit

Note: I know that best coding practice dictates that I rollback in the catch. 注意:我知道最佳编码实践决定了我回过头来。 This is just a behavioral question that I have wondered about. 这只是我想知道的一个行为问题。

To determine how MySQL handles transactions when a connection (session) is terminated, we have to consider whether autocommit mode is enabled or not. 为了确定当连接(会话)终止时MySQL如何处理事务,我们必须考虑是否启用了autocommit模式。

  1. If autocommit is disabled and the connection is terminated before a commit, then the last open transaction is rolled back : 如果禁用了自动提交,并且在提交之前终止了连接,那么将回滚上一个打开的事务

If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that transaction. 如果禁用了自动提交的会话在没有显式提交最终事务的情况下结束,则MySQL将回滚该事务。

Note, start transaction does implicitly disable autocommit for the duration of the transaction: 注意, start transaction确实会在事务期间隐式禁用自动提交

With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. 使用START TRANSACTION,自动提交将保持禁用状态,直到您使用COMMIT或ROLLBACK结束事务。 The autocommit mode then reverts to its previous state. 然后,自动提交模式将恢复为之前的状态。

  1. If autocommit is enabled, then any successful data modification is committed anyway. 如果启用了自动提交,则无论如何都会成功提交任何成功的数据修改。 If the data modification statement causes an error, then obviously the changes will not be committed (well, there is no change in this case). 如果数据修改语句导致错误,则显然不会提交更改(当然,在这种情况下没有更改)。 So, terminating the connection does not make any difference in this case. 因此,在这种情况下,终止连接没有任何区别。

However, as @MarkBaker also pointed out, it still may be a good idea to explicitly roll back the transaction if an error was detected to make the point clear to all readers of the code. 但是,正如@MarkBaker也指出的那样,如果检测到错误以使所有代码读者都明白这一点,则显式回滚事务仍然是一个好主意。 Remember, you yourself was not clear on how this exactly works and other php programmers may have the same question if they do not see an explicit rollback in your code. 请记住,您自己尚不清楚这是如何工作的,如果其他php程序员在您的代码中未看到显式回滚,则可能会有相同的问题。

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

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