3

我真的不明白如何在 DBAL 中进行交易

我有以下脚本将根据行的 id 更新列。我放了一个在表中不存在的假 id,(因此无法进行更新)但是尽管它是一个事务,但第一次更新被提交。如果其中一项失败,我希望所有交易都会失败。

 $conn -> beginTransaction();
   try{
       $try = $conn->prepare("update table set column = '123' where id = 0"); //column exists
       $try->execute();
       $try = $conn->prepare("update table set column = '123' where id = 1"); //column exists
       $try->execute();
       $try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists
       $try->execute();

       $try = $conn->commit();
   }
   catch(Exception $e) {
       $try = $conn->rollback();
       throw $e;
   }

预期结果,没有更新,因为 id = 120 的行不存在 真实结果,所有行都被更新,除了不存在的行。

我提前道歉,但面向对象编程对我来说仍然是南极洲。

4

2 回答 2

3

我知道这个问题已经很老了,所以如果将来有人遇到类似的问题,我会稍微解释一下,因为这种行为不是错误。

$try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists
$try->execute();

这里更新条件引用了一个不存在的列,所以查询不会失败,它会更新 0(零)行;在 Doctrine 中,受影响的行数由execute()方法返回。

您可以抛出异常来触发回滚。

$try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists
$affected = $try->execute();
if ($affected == 0) {
  throw new Exception('Update failed');
}
于 2012-01-27T14:13:38.403 回答
1

此代码仅在抛出异常时回滚事务。

当更新不成功时,它返回false,而不是异常。

您可以尝试没有例外:

$try = $conn->commit();
if (!$try) {
   $conn->rollback();
}

或当结果为false.

于 2011-07-23T07:39:50.120 回答