php - 抛出数据库错误异常时可以回滚事务吗?

标签 php mysql cakephp cakephp-2.3

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

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

这是我的 Controller 的操作。

/**
 * 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.');
}

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

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

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

最佳答案

你可以做:

$dataSource->begin();

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

$dataSource->commit();

关于php - 抛出数据库错误异常时可以回滚事务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884108/

相关文章:

mysql - 如何在一个查询中两次使用表中的相同字段

mysql - SQL 查询(排序街道地址)

mysql - 在 Doctrine 模式中,当我添加新字段时无法更新

CakePHP 检查 session 存在于数据库中

php - 使用php从ms access db获取最大和最小时间

php - 优化性能 : Many CURL requests

javascript - Codeigniter jquery ajax登录: get value from database and compare data entered

php - 如何使用 PHP 在 Open Street Map 中绘制路线

php - 选择输入中的数据分组。蛋糕PHP

cakephp 分页器非常慢