gpt4 book ai didi

php - 原则 DBAL 交易

转载 作者:可可西里 更新时间:2023-11-01 01:08:01 24 4
gpt4 key购买 nike

我不太明白如何在 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 的行不存在真实结果,除了不存在的行外,所有行都被更新。

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

最佳答案

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

$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');
}

关于php - 原则 DBAL 交易,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6798613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com