【问题标题】:Database error with CodeIgniter, Why does it want to do identity insert?CodeIgniter 出现数据库错误,为什么要进行身份插入?
【发布时间】:2019-01-21 10:25:51
【问题描述】:

我有一个基于 CodeIgniter 的 Web 应用程序,以前使用的是 MySQL 数据库。迁移所有数据/表后,我更改了 database.php 以将其连接到 SQL Server。我现在正在测试应用程序并且登录成功。但是,当从 Web 应用程序中的表单添加对象时,它会在插入查询时引发错误。

错误提示当 ID Insert 属性打开时,它无法插入到guests 表中。

发生数据库错误

错误号:23000/544

[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]无法插入 表 'guests' 中标识列的显式值 IDENTITY_INSERT 设置为 OFF。

INSERT INTO "guests" ("id", "firstname", "lastname", "gender", "dob",
 "email", "country_id", "state_id", "city_id", "address", "mobile",
 "id_type", "id_no", "remark", "vip", "password", "added") VALUES (0,
 'abc', '123', '1', '', 'abc123@123.com', '', '', '', '', '899834534',
 '', '', '', 0, '6367c48dd193d56ea7b0baad25b19455e529f5ee', '2019-01-21
 09:58:11')

文件名:C:/wamp64/www/hms/system/database/DB_driver.php 行号: 691

我知道解决方法是 T-SQL SET IDENTITY_INSERT guests ON,但为什么这些插入查询要以这种方式构造?

我检查了 DB_Driver.php,这可能是相关部分

/**
     * Generate an insert string
     *
     * @param   string  the table upon which the query will be performed
     * @param   array   an associative array data of key/values
     * @return  string
     */
    public function insert_string($table, $data)
    {
        $fields = $values = array();

        foreach ($data as $key => $val)
        {
            $fields[] = $this->escape_identifiers($key);
            $values[] = $this->escape($val);
        }

        return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
    }

    // --------------------------------------------------------------------

    /**
     * Insert statement
     *
     * Generates a platform-specific insert string from the supplied data
     *
     * @param   string  the table name
     * @param   array   the insert keys
     * @param   array   the insert values
     * @return  string
     */
    protected function _insert($table, $keys, $values)
    {
        return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
    }

如何对项目进行更改,使其不会尝试在每个插入查询中插入 Identity 列?

编辑: 上面的代码摘录很可能不是查询形成的地方,因为我改了,错误依旧。

【问题讨论】:

标签: php sql-server codeigniter


【解决方案1】:

您误解了错误消息。让我们再次引用它:

无法为表“guests”中的标识列插入显式值 当 IDENTITY_INSERT 设置为 OFF 时

您的表有一个标识列,即id。错误消息明确告诉您,当 IDENTITY_INSERT 设置为 off 时,您无法为标识列 (id) 指定显式值。 IDENTITY_INSERT 是一个设置,用于确定是否允许标识列使用显式值。由于不允许,因此应出现错误消息。您可以打开IDENTITY_INSERT,也可以在表格中插入一行时避免指定id 的值。

【讨论】:

  • 你好 Lajos,也许我不清楚——英语不是我的母语。 DB_Driver.php 是所有 CodeIgniter 项目的核心代码。 example here我问这个问题是因为我在这里缺少什么吗?其他人如何将 CI 与 SQL Server 一起使用?我应该使用其他 DB_Driver.php 文件吗?
  • @nts 我从未使用过 Code Igniter,但问题来自 SQL Server。问题是 CodeIgniter 最终会尝试插入记录,并指定它们的 id,但这对于表来说是不允许的。所以你要么插入没有 id 的记录(所以 id 会自动从 SQL Server 获取一个值),或者你改变表的设置。
猜你喜欢
  • 1970-01-01
  • 2019-11-26
  • 2020-08-06
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 2012-10-30
相关资源
最近更新 更多