5

I have a sqlite table (sqlite version 3.7.3) where nulls inserted into the primary key column are being undesirably auto-incremented:

sqlite> CREATE TABLE foo(bar INTEGER NOT NULL PRIMARY KEY);
sqlite> INSERT INTO foo(bar) VALUES(NULL);
sqlite> SELECT * FROM foo;
1

In the sqlite docs, it shows that adding the AUTOINCREMENT keyword to the column should create this behavior, but there doesn't appear to be a keyword to prevent the auto incrementing...

I also found that I can build sqlite with the SQLITE_OMIT_AUTOINCREMENT compile option, but I don't want to disable the behavior globally, just for this particular column.

Interestingly, if I don't include the PRIMARY KEY constraint, I get the desired behavior:

sqlite> CREATE TABLE FOO(bar integer NOT NULL);
sqlite> INSERT INTO FOO(bar) VALUES(NULL);
SQL error: foo.bar may not be NULL

How can I define the table so that NULL values are rejected and keep the primary key constraint?

4

2 回答 2

9

自动增量行为仅适用于声明为 的列INTEGER PRIMARY KEY。因此,禁用它的最简单方法是:

  • 将列声明为,UNIQUE而不是PRIMARY KEY
  • 将列类型声明为INT而不是INTEGER

请注意,任何一个都会为您提供具有整数亲和力的列,而不是被限制为仅包含整数。

于 2013-06-11T21:46:50.197 回答
-2

当您需要插入数据时,禁用自动增量(在重新创建表之外)的一种方法是使用 sqlite3 中的导入工具:

如果你有这样的表:

CREATE TABLE [table1] ( [ID] integer PRIMARY KEY AUTOINCREMENT NOT NULL, [col1] TEXT);

如果您使用数据文件对其运行导入命令:

ID col1
10 abc
20 def

import myfile.txt table1

它将导入行,并且将忽略自动增量功能。

于 2015-01-15T16:47:15.550 回答