简体   繁体   English

PDO多个查询:提交和回滚事务

[英]PDO Multiple queries: commit and rollback transaction

I need to fire 2 queries. 我需要触发2个查询。 currently I'm doing it like this: 目前,我正在这样做:

// Begin Transaction
$this->db->beginTransaction();

// Fire Queries
if($query_one->execute()){
    if($query_two->execute()){

        // Commit only when both queries executed successfully
        $this->db->commit();

   }else{
        $this->db->rollback();
   }
}else{
    $this->db->rollback();
}

Is this the correct approach? 这是正确的方法吗? I'm not using any try..catch in my code will it make my code inappropriate or vulnerable for any situation? 我在代码中没有使用try..catch,这会使我的代码在任何情况下都不适当或容易受到攻击吗?

Yes, your approach is correct. 是的,您的方法是正确的。 Using Try...catch may lead into cleaner and more readable code in some cases but your overall approach is fine. 在某些情况下,使用Try...catch可能会导致代码更清晰,可读性更好,但是您的总体方法还不错。

If your code fragment is from a function that handles DB queries and not much else, I'd probably switch the approach around: 如果您的代码片段来自于处理数据库查询的函数,而其他则不多,那么我可能会改变方法:

// Begin Transaction
$this->db->beginTransaction();

// Fire Queries
if(!$query_one->execute()){
    $this->db->rollback();
    // other clean-up goes here
    return;
}

if(!$query_two->execute()){
    $this->db->rollback();
    // other clean-up goes here
    return; 
}

$this->db->commit();

Of course, if you require lots of clean-up to be done before you can return , then your original approach is better. 当然,如果在return之前需要进行大量清理,那么原始方法会更好。 Especially in these cases I'd look into using PDO::ERRMODE_EXCEPTION. 特别是在这些情况下,我会考虑使用PDO :: ERRMODE_EXCEPTION。 This has some additional benefits, like exceptions automatically rolling back the transaction unless they are caught. 这还有一些其他好处,例如,除非被捕获,否则异常会自动回滚事务。

You need to wrap your transaction inside a try-catch. 您需要将交易包装在try-catch中。 Mostly, if an exception is thrown, there is something wrong that your process can not continue. 通常,如果引发异常,则说明您的过程无法继续进行,这是有问题的。 You don't know where the exception will come from, right? 您不知道异常的来源,对不对? So, instead of letting the exception thrown wildly and force the application to stop, it is better to catch it, rollback the database transaction, and rethrow it. 因此,与其让异常抛出异常并迫使应用程序停止,不如捕捉它,回滚数据库事务并重新抛出它。

// Begin Transaction
$this->db->beginTransaction();

try {

    $queryOne->execute();
    $queryTwo->execute();

    $this->db->commit();

} catch (\Exception $e) {
    $this->db->rollback();
    throw $e;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM