如何向仅包含一列且具有自增主键的sqlite表插入数据?

Rom*_*man 3 python sqlite insert primary-key auto-increment

我想在 sqlite 中有一个“计数器”表,它总是给我一个新的唯一 ID。我通过以下方式管理了我需要的内容。首先,我创建下表:

cursor.execute('''create table second (id integer primary key autoincrement, age integer)''')
Run Code Online (Sandbox Code Playgroud)

然后我执行以下命令序列:

cursor.execute('''insert into second (age) values (1)''')
cursor.lastrowid
Run Code Online (Sandbox Code Playgroud)

每次执行以上两列时,我都会得到一个新整数。这正是我所需要的。然而,上述解决方案并不优雅,因为我使用了我并不真正需要的列(“年龄”)。我使用的原因如下。我可以创建一个仅包含一列且具有 ID 的表:

cursor.execute('''create table first (id integer primary key autoincrement)''')
Run Code Online (Sandbox Code Playgroud)

但是,问题是我无法插入到该表中。以下不起作用:

cursor.execute('''insert into first () values ()''')
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

sqlite3.OperationalError: near ")": syntax error
Run Code Online (Sandbox Code Playgroud)

有人知道如何解决所描述的问题吗?

Gab*_*aru 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
Run Code Online (Sandbox Code Playgroud)