PHP,MySQL,PDO事务-try块中的代码是否在commit()处停止? [英] PHP, MySQL, PDO Transactions - Does the code inside try block stop at commit()?

查看:71
本文介绍了PHP,MySQL,PDO事务-try块中的代码是否在commit()处停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对交易还很陌生.

之前,我正在做的事情是这样的:

Before, what I was doing was something like:

代码块1

$db = new PDO(...);

$stmt = $db->prepare(...);

if($stmt->execute()){
    // success
    return true;
}else{
    // failed
    return false;
}

但是,为了将多个查询分组到一个事务中,我现在使用的是类似的东西:

But in an attempt to group multiple queries into a single transaction, I'm now using something like:

代码块2

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->beginTransaction();

try{
    $stmt = $db->prepare(... 1 ...);
    $stmt->execute();

    $stmt = $db->prepare(... 2 ...);
    $stmt->execute();

    $stmt = $db->prepare(... 3 ...);
    $stmt->execute();

    $db->commit();

    return true;
}catch(Exception $e){
    // Failed, maybe write the error to a txt file or something
    $db->rollBack();
    return false;
}

我的问题是:如果由于某种原因交易失败,代码是否会在$db->commit();处停止并跳转到catch块?还是先运行return true;,然后尝试进入catch?因为是这种情况,那么我已经回来了,所以不会去catch了.并且它将返回错误的值.

My question is: If the transaction fails for whatever reason, does the code stop at $db->commit(); and jump to the catch block? Or would the return true; run first, and then it would try to go to the catch? 'Cause if that's the case, then I've already returned, and so it wouldn't go to the catch. AND it would have returned the wrong value.

我是否还需要包含类似内容:

Do I still need to include something like:

代码块3

if($stmt->commit()){
    return true;
}

或者用我在代码块2 中编写的方式是否足够?

or is it sufficient the way I have it written in Code Block 2?

推荐答案

如果事务由于某种原因而失败,则代码会在发生错误的那一行停止结束,然后执行直接跳转到捕获块.因此,用代码块2编写代码的方式就足够了.

If the transaction fails for whatever reason, the code does stop at the very line where error occurred end then the execution jumps directly to the catch block. So it is sufficient the way you have it written in Code Block 2.

请注意,您应该在回滚后始终重新抛出异常..否则,您将永远不知道出了什么问题.所以应该是

Note that you should always re-throw the Exception after rollback. Otherwise you will never have an idea what was a problem. So it should be

try{
    $stmt = $db->prepare(... 1 ...);
    $stmt->execute();

    $stmt = $db->prepare(... 2 ...);
    $stmt->execute();

    $stmt = $db->prepare(... 3 ...);
    $stmt->execute();

    $db->commit();

    return true;
}catch(Exception $e){
    $db->rollBack();
    throw $e;
}

这篇关于PHP,MySQL,PDO事务-try块中的代码是否在commit()处停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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