PDO Multiple queries: commit and rollback transaction

邮差的信 提交于 2019-12-02 15:37:36

问题


I need to fire 2 queries. 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?


回答1:


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.

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. Especially in these cases I'd look into using PDO::ERRMODE_EXCEPTION. This has some additional benefits, like exceptions automatically rolling back the transaction unless they are caught.




回答2:


You need to wrap your transaction inside a 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;
}


来源:https://stackoverflow.com/questions/22890767/pdo-multiple-queries-commit-and-rollback-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!