我真的不了解如何在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的行不存在真实结果,除了不存在的行之外,所有行都被更新。
我提前道歉,但面向对象编程对我来说仍然是南极洲。
发布于 2012-01-27 22:13:38
我知道这个问题很老了,所以如果将来有人遇到类似的问题,我会稍微解释一下,因为这种行为不是错误。
$try = $conn->prepare("update table set column = '123' where id = 120"); //column does not exists
$try->execute();在这里,update条件引用了一个不存在的列,因此查询不会失败,它将更新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');
}发布于 2011-07-23 15:39:50
此代码仅在抛出异常时回滚事务。
当更新不成功时,它返回false,而不是异常。
您可以无一例外地尝试:
$try = $conn->commit();
if (!$try) {
$conn->rollback();
}或者当result为false时抛出异常。
https://stackoverflow.com/questions/6798613
复制相似问题