DBD::SQLite::st 执行失败:ID 不能为 NULL

DBD::SQLite::st execute failed: ID may not be NULL

我尝试使用 Perl 在 SQLite 数据库的 table 中插入一行。 table 的列 ID 设置了 AUTOINCREMENTPRIMARY KEY 属性。

来自 MY_TABLE 架构,这是关于 ID 字段的所有信息:

ID [INT AUTO_INCREMENT] NOT NULL,
PRIMARY KEY (ID)

我不想为添加的每个新行配置 ID,因此我尝试了几种让数据库自行更新的方法,但我得到:

DBD::SQLite::st execute failed: MY_TABLE.ID may not be NULL

use DBI;
my $db = DBI->connect("...");
my $sql = qq{
    insert into MY_TABLE (ID, col_b, col_c, col_d)
    values(?, ?, ?, ?)
}

my $st = $db->prepare($sql);
$st->execute(undef, 'val2', 'val3', 'val4');

我还尝试从查询和参数中完全跳过参数,但结果相同。将 0 而不是 undef 插入实际值(我不想这样做,我希望自动递增)。

我错过了什么?

我怀疑您不应该将空值传递给列,而应该传递列本身。

尝试:

use DBI;
my $db = DBI->connect("...");
my $sql = qq{
    insert into MY_TABLE (col_b, col_c, col_d)
    values(?, ?, ?)
}

my $st = $db->prepare($sql);
$st->execute('val2', 'val3', 'val4');

正如其他地方提到的,正确的拼写是 AUTOINCREMENT,而不是 AUTO_INCREMENT,但没关系,您真正需要的是声明您的 ID 字段 INTEGER PRIMARY KEY 那样,INT 不够好,而且您通常不需要 AUTOINCREMENT 关键字(请参阅 https://sqlite.org/lang_createtable.html),并且不要指定任何内容在您的 INSERT 声明中输入 ID。

ID [INT AUTO_INCREMENT] NOT NULL,
PRIMARY KEY (ID)
  1. AUTOINCREMENT(不是 AUTO_INCREMEMENT)仅适用于 INTEGER PRIMARY KEY 列(并且通常不应该被使用,因为它并不像名称所暗示的那样;details).
  2. 大多数 sqlite table 都有一个带符号的 64 位整数的主键(rowid). When inserting a new row, if a rowid value is absent or NULL, a new one is generated automatically (This is what people think AUTOINCREMENT does because they're used to how other databases work). An INTEGER PRIMARY KEY column acts an alias for the rowid and behaves the same way. Any other primary key is equivalent to a unique index on that column(s). The column affinity has to be INTEGER for a rowid alias. Nothing else, like INT. More reading.

所以,基本上,将您的 table 定义更改为包含

id INTEGER PRIMARY KEY

相反,您可以将其从 INSERT 中删除或分配给它 NULL,它会按您想要的方式工作。