问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/52881466/cancel-a-transaction-in-mysql-innodb-instead-of-commit-or-rollback