简体   繁体   中英

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. Does it automatically rollback since the connection to the database is dropped from PHP or will a lock remain in place?

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.

  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.

Note, start transaction does implicitly disable autocommit for the duration of the transaction:

With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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