简体   繁体   中英

cancel a transaction in MySQL InnoDB instead of commit or rollback

I am using a transaction in a MySQL InnoDB database to perform 2 inserts. However, if the first insert fails, I would like to simply "cancel" the transaction. Is there a good approach to "cancel" the transaction rather than using commit or rollback ?

For example, in php, I am doing the following:

$connection->beginTransaction();
$affectedRows = $tableOne->insertIgnore('example data');
if ($affectedRows == 0) {
    $connection->rollback();
} else {
    $tableTwo->insert('more example data');
    $connection->commit();
}

As you can see, I am using rollback to cancel the transaction, but this is a misnomer because there actually is nothing to rollback.

There is really no concept of canceling a transaction. Instead, you need to do a rollback . Alternatively, you can also do nothing. If the connection object has an uncommitted transaction when it goes out of scope, or it is otherwise closed, the transaction will automatically be rolled back.

In other words, it's alright if there is nothing to rollback, because underneath the hood, the DB driver will handle this case gracefully.

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