PDO :: commit()成功或失败 [英] PDO::commit() success or failure

查看:94
本文介绍了PDO :: commit()成功或失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP PDO :: commit()文档指出,如果成功,则方法返回TRUE,否则返回FALSE.这是指beginTransaction()和commit()之间语句执行的成功还是失败?

The PHP PDO::commit() documentation states that the method returns TRUE on success or FALSE on failure. Does this refer to the success or failure of the statement executions between beginTransaction() and commit()?

例如,从文档中:

$dbh->beginTransaction();
$sql = 'INSERT INTO fruit (name, colour, calories) VALUES (?, ?, ?)';
$sth = $dbh->prepare($sql);

foreach ($fruits as $fruit) {
    $sth->execute([
        $fruit->name,
        $fruit->colour,
        $fruit->calories,
    ]);
}

$dbh->commit();

如果上述任何执行失败,由于原子事务的全有或全无"基础,commit()方法会返回false吗?

If any of the above executions fail, will the commit() method return false due to the "all-or-nothing basis" of atomic transactions?

推荐答案

返回值基于pdo :: commit本身,而不是您要提交的事务. 当没有事务处于活动状态时,它将返回FALSE,但是何时返回TRUE或FALSE并不清楚.

The return value is based on pdo::commit itself, not the transaction you're trying to commit. It returns FALSE when there's no transaction active, but it's not very clear whenever it should return TRUE or FALSE.

在事务本身中执行的查询本身将成功或失败. 以Mr.Tk为例,如果可能,事务将被提交,并且在"try"块中执行查询时不会发生错误,如果在"try"块中确实发生了错误,则回滚.

The executed queries within the transaction itself will success or fail on it's own. Using the Mr.Tk's example, the transaction will be committed if possible and no error occured while executing the queries in the "try" block and rolled back if an error did occur within the "try" block.

仅在"try"块中评估执行的查询时,我个人将尝试捕获PDOException而不是普通的Exception.

When only evaluating the executed queries within the "try" block, personally I would try to catch a PDOException instead of a normal Exception.

$dbh->beginTransaction();
try {
    // insert/update query
    $dbh->commit();
} catch (PDOException $e) {
    $dbh->rollBack();
}

这篇关于PDO :: commit()成功或失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆