我在处理事务时通常使用的 idea 如下:
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$db->query('first query');
$db->query('second query');
$db->query('third query');
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();
} catch (\Throwable $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
throw $e; // but the error must be handled anyway
}
Note that, with this idea, if a query fails, an Exception must be thrown:
- PDO can do that, depending on how you configure it
- 否则,使用其他API时,您可能必须测试用于执行查询的函数的结果,然后自己抛出异常.
Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.
例如,通常在事务(before the 100)之前会有两个查询,在事务(after either 101 or 102)之后会有两个查询,并且无论事务(or not)中发生了什么,您都希望执行这些查询.