【问题标题】:Can I rollback transaction when database error exception is thrown?抛出数据库错误异常时可以回滚事务吗?
【发布时间】:2013-04-08 16:16:40
【问题描述】:

我有一个大型数据集需要在发布到服务器时写入数据库,但可能是客户端编辑器中的错误添加了触发“完整性约束违规”的额外记录。

我的问题是,当我到达触发错误的数据点时,数据库中已经更新了很多以前的数据。我需要回滚并拒绝发布的数据。

这是我的控制器的操作。

/**
 * Handles saving data from the network editor.
 */
public function json_save()
{
    if($this->request->is('post'))
    {
        $result = array();
        $data = $this->request->input('json_decode');
        if(isset($data->network_id) && !empty($data->network_id))
        {
            $dataSource = $this->Node->getDataSource();
            $dataSource->begin();

            $result['nodes'] = $this->updateModel($data->network_id, $this->Node, 'nodes', $data, array(
                'ParamValue'
            ));
            $result['connections'] = $this->updateModel($data->network_id, $this->Connection, 'connections', $data);

            $dataSource->commit();

            $this->viewClass = 'Json';
            $this->set('result', $result);
            $this->set('_serialize', array(
                'result'
            ));

            return;
        }
    }

    throw new ErrorException('Posted data missing.');
}

我的控制器的updateModel 函数对模型$this->Node 和$this->Connection 执行一些删除和更新。

如何回滚在更新$this->Connection 模型期间通常抛出的“完整性约束违规”。

我不确定它是否是我可以捕获然后执行回滚的 PHP 异常,或者是否有其他方法可以捕获它。

【问题讨论】:

    标签: php mysql cakephp cakephp-2.3


    【解决方案1】:

    你可以做一个:

    $dataSource->begin();
    
    try {
      // The queries here.
    } catch (Exception $e) {
      $dataSource->rollback();
      throw $e;
    }
    
    $dataSource->commit();
    

    【讨论】:

      猜你喜欢
      • 2011-06-29
      • 2020-09-24
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多