简体   繁体   English

使用PDO的交易

[英]Transactions using PDO

My understanding is the InnoDB is now the default engine for MySQL. 我的理解是InnoDB现在是MySQL的默认引擎。 With that knowledge, I am beginning to delve into transactions. 有了这些知识,我就开始研究交易。

Here is what I have so far... 这是我到目前为止所拥有的...

try{
     $pdo->beginTransaction();
        $stmnt = $pdo->prepare ("delete from playing where uniq = :uniq");
        $stmnt->bindParam (':uniq',$uniq);
        $stmnt->execute();

        $stmnt = $pdo->prepare ("insert into removals (playdate, time, vid) values (:playdate, :time, :vid");
        $stmnt->bindParam (":playdate",$playdate);
        $stmnt->bindParam (":time", $time);
        $stmnt->bindParam (":vid", $vid);
        $stmnt->execute();

     $pdo->commit();

     echo "1"; // success
     return;
   }
   catch (PDOException $e){
      $pdo->rollback();
      echo $e->getMessage();
   }

This is called by jQuery with a result of "1" indicating a success. jQuery调用它,结果为“ 1”表示成功。

If I understand this correctly, if bot statements execute successfully, they will both be "committed" however it either fails, no database activity will take place and an error message will be generated detailing the first statement execution that fails. 如果我正确理解,如果bot语句成功执行,它们都将被“提交”,但是要么失败,就不会发生数据库活动,并且将生成一条错误消息,详细说明第一个失败的语句执行。

My real question is whether the begin transaction and commit should reside within or outside the try...catch block. 我真正的问题是,开始事务和提交应该位于try ... catch块之内还是之外。

Thanks, -dmd- 谢谢-dmd-

For readability and cleanliness, yes it should be inside the try block. 为了可读性和清洁性,是的,它应该放在try块中。 But it really does not matter. 但这真的没关系。 It just declares what to commit or rollback if you call roll back. 如果调用回滚,它仅声明要提交或回滚的内容。

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

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