【问题标题】:Transactions in php function or in mysql stored procedure?php函数或mysql存储过程中的事务?
【发布时间】:2015-06-12 12:59:13
【问题描述】:

开始交易的更好方法是什么? 内部过程还是 PHP 函数?

例如我这样调用 MySQL 程序:

function sendLeaguesToDb(){ 
    $leagues = "";
    try{
        $this->PDO->beginTransaction();
        $stmt = $this->PDO->prepare("call insupd_Leagues(:id,:name,:country,:sport_id,:his_data,:fixtures,:livescore,
        :numofmatches,:latestmatch)");
        $leagues=$this->soccer->GetAllLeagues();
        foreach($leagues as $key=>$value){
           $stmt->bindParam(':id',$value->Id);
           $stmt->bindParam(':name',$value->Name);  
           $stmt->bindParam(':country',$value->Country);
           $stmt->bindParam(':sport_id',$value->Sport_Id);
           $stmt->bindParam(':his_data',$value->Historical_Data);
           $stmt->bindParam(':fixtures',$value->Fixtures);
           $stmt->bindParam(':livescore',$value->Livescore);
           $stmt->bindParam(':numofmatches',$value->NumberOfMatches);
           $stmt->bindParam(':latestmatch',$value->LatestMatch);
           $stmt->execute();
           $this->PDO->commit();
        }
    }
    catch(XMLSoccerException $e){
        echo "XMLSoccerException: ".$e->getMessage();
    }
    catch(PDOException $e){
        echo "PDOException: ".$e->getMessage();
        $this->PDO->rollback();
    }
}

如果我想每分钟/小时尽可能快地发送/获取数据,这是一种好方法吗?

【问题讨论】:

  • 这是您可以轻松地对自己进行基准测试的东西。
  • 你到底是什么意思?
  • @user1814358:您可以执行两个包含该代码的不同文件,例如运行代码 10000 次,然后您只需计算哪个运行时间更长,您就会得到答案。

标签: php mysql pdo transactions


【解决方案1】:

这取决于您要达到的目标。

如果您想将所有插入视为“原子操作”,您做对了,就像对 SP 的一次调用失败一样,回滚将撤消之前调用所做的所有更改

否则,如果您想“隔离”每个 SP 调用,并确保如果成功将结果存储在数据库中,则您必须在 SP 内启动和结束事务

我认为首选的解决方案是第一个

编辑:我现在注意到一件事:提交应该在 for 之后:

try{
    $this->PDO->beginTransaction();
    $stmt = $this->PDO->prepare("call insupd_Leagues(:id,:name,:country,:sport_id,:his_data,:fixtures,:livescore,
    :numofmatches,:latestmatch)");
    $leagues=$this->soccer->GetAllLeagues();
    foreach($leagues as $key=>$value){
       $stmt->bindParam(':id',$value->Id);
       $stmt->bindParam(':name',$value->Name);  
       $stmt->bindParam(':country',$value->Country);
       $stmt->bindParam(':sport_id',$value->Sport_Id);
       $stmt->bindParam(':his_data',$value->Historical_Data);
       $stmt->bindParam(':fixtures',$value->Fixtures);
       $stmt->bindParam(':livescore',$value->Livescore);
       $stmt->bindParam(':numofmatches',$value->NumberOfMatches);
       $stmt->bindParam(':latestmatch',$value->LatestMatch);
       $stmt->execute();

    }    
   //move your commit here   
   $this->PDO->commit();

}

【讨论】:

  • 所以在我的情况下最好这样离开。谢谢。
  • 我不知道为什么要在 foreach 中提交,我知道它应该出来了... :O 谢谢...
猜你喜欢
  • 2012-04-15
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 2018-11-25
相关资源
最近更新 更多