cancel a transaction in MySQL InnoDB instead of commit or rollback

帅比萌擦擦* 提交于 2019-12-11 19:14:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!