【问题标题】:Suggestion, php mysql transaction for insertion to multiple tables in a block建议,php mysql transaction for inserts to multiple tables in a block
【发布时间】:2012-11-26 05:13:12
【问题描述】:

我需要对一段代码使用事务,它由多个插入组成。在 try catch 块中包含整个代码块是否是一个好习惯,在 try..catch 块之前开始事务。然后对于任何捕获的异常回滚其他事务提交。

基本问题:

  • 在单个事务周期中包含整个代码块是不好的做法吗?
  • 如果这是一种不好的做法,那么处理这个问题的好方法是什么?为什么?

这是一段代码:

    $con = Propel::getConnection(SomeTablePeer::DATABASE_NAME);        
    $con->beginTransaction();        
    try {
        $currentRevision = $budgetPeriod->getRevision();
        $newRevision = $currentRevision->copy();
        $newRevision->setIdclient($client->getIdclient());            
        $newRevision->setIsLocked(0);
        $newRevision->save();
        $currentRevision->setEffectiveTo($currentDate);
        $currentRevision->save();

        $currentRevisionHasCorporateEntities = $currentRevision->getCorporateEntitys();
        $newOldCorporateEntitiesRelations = array(); 

        foreach ($currentRevisionHasCorporateEntities as $currentRevisionHasCorporateEntity) {

            $newRevisionHasCorporateEntity = $currentRevisionHasCorporateEntity->copy();                
            $newRevisionHasCorporateEntity->save();
        }

     // this continues for a while there are a whole list of insertions based on previous insertion and on and on.
    }catch (Exception $exc) {
        $con->rollback();            
        $this->getUser()->setFlashError('Error occured! Transaction Failed');
    }

【问题讨论】:

    标签: php mysql transactions symfony-1.4 propel


    【解决方案1】:

    实际上,我们应该专注于较小的事务边界,这样我们就可以避免在 Db 中发生任何锁定,但有时我们需要执行或不执行整个代码块,所以在这种情况下,我们几乎没有机会了,你需要尽可能地模块化你的代码。

    【讨论】:

      【解决方案2】:

      这里需要注意的是,无论try块有多大,我们都应该能够捕捉到它抛出的异常并采取相应的措施。

      但是这里你用过

      catch (Exception $exc)
      

      您将无法捕获不同的异常。这有助于调试和显示异常的正确原因。

      另外,如果它是一个事务,我们必须将它放在一个 try 块中

      【讨论】:

      • “您将无法捕获不同的异常”是什么意思。如果您指的是针对不同异常的不同 catch 块,我在我的代码中确实有它,例如,我只是使用了更通用的方法。顺便说一句,我相信这可以捕获所有例外情况,尽管这不是最好的做法。
      • 这就是我的意思——“顺便说一句,我相信这可以捕获所有异常,尽管这不是最好的做法”
      猜你喜欢
      • 2022-12-28
      • 2022-12-02
      • 2022-12-02
      • 1970-01-01
      • 2022-12-01
      • 2010-09-23
      • 2022-12-01
      • 2020-09-30
      • 2022-12-26
      相关资源
      最近更新 更多