PDO beginTransaction rollback function

时间:2019-04-17 01:55:43

标签: database pdo transactions

I'm new to PDO transaction, I want to know is the rollback() is rollback the database or only the tables inside the beginTransaction().

For example :

$db->beginTransaction();
try{
    $stmt = $db->prepare('SELECT * FROM user_detail .......');
    $stmt -> bindParam(........);
    ......
    $stmt -> execute();
    while($s = $stmt->fetch(PDO::FETCH_ASSOC)){
        $update = $db->prepare('UPDATE tableB .......');
        $update -> execute();
        $update = $db->prepare('UPDATE tableC .......');
        $update -> execute();
        $delete = $db->prepare('Delete tableD .......');
        $delete -> execute();

    }
    $db->commit();
}
catch(PDOException $e){
    $db->rollback();
}

At the same time, there is another query which will update tableC and tableG been submitted when the first query (shown above) still executing. Will the new query execute immediately or after the first query has done.

If both of them execute at the same time, what if there is an error found and trigger the rollback(), will the second query (update tableC and tableG) rollback if it is done before the rollback start?

1 个答案:

答案 0 :(得分:0)

回滚将撤消自事务开始以来INSERT / UPDATE / DELETE所做的所有更改。

无论您提交还是回滚,只有那些在当前事务中进行的更改,而不是在其他会话中进行的其他更改。他们可以独立地进行提交或回滚。

在不同会话中运行的并发更新将同时运行,除非它们试图更新相同的行(甚至是部分重叠的行集)。一个会话或另一个会话将首先到达这些行,并在更新它们之前将其锁定。获得锁的会话将持有这些锁,直到它提交或回滚其事务。

还有很多关于锁定的知识。这是一个非常复杂的主题。您可能希望我的演示文稿InnoDB Locking Explained with Stick Figures开始使用(但只是刮伤了表面)。

我的演讲专门关于MySQL。您没有说您正在使用什么品牌的RDBMS。所有不同的品牌在交易和锁定方面都有各自的特点。