如何向只包含自增主键的一列的sqlite表中插入数据?

3 投票
2 回答
3615 浏览
提问于 2025-04-18 08:49

我想在sqlite中创建一个“计数器”表,这样我每次都能得到一个新的唯一ID。我已经找到了一种方法来实现这个需求。首先,我创建了以下这个表:

cursor.execute('''create table second (id integer primary key autoincrement, age integer)''')

然后我执行以下一系列命令:

cursor.execute('''insert into second (age) values (1)''')
cursor.lastrowid

每次我执行上面的两个命令时,我都会得到一个新的整数。这正是我需要的。不过,这个解决方案不太优雅,因为我用了一个我其实不需要的列(“age”)。我之所以这么做,是因为我可以创建一个只包含ID的表:

cursor.execute('''create table first (id integer primary key autoincrement)''')

但是,问题是我无法往这个表里插入数据。下面的操作是行不通的:

cursor.execute('''insert into first () values ()''')

我得到了以下错误信息:

sqlite3.OperationalError: near ")": syntax error

有没有人知道怎么解决这个问题呢?

2 个回答

3

文档中提到:

如果在插入数据时没有指定ROWID,或者指定的ROWID值为NULL,那么系统会自动生成一个合适的ROWID。

所以你可以明确地指定NULL:

INSERT INTO first(id) VALUES(NULL)

或者根本不指定任何值:

INSERT INTO first DEFAULT VALUES
5

这个应该可以用:

sqlite> CREATE TABLE first (id integer primary key autoincrement);
sqlite> INSERT INTO first (id) VALUES (null);
sqlite> SELECT * FROM first;
1
sqlite> INSERT INTO first (id) VALUES (null);
sqlite> SELECT * FROM first;
1
2

撰写回答