Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何插入到只包含一个具有自动增量主键的列的sqlite表中?_Python_Sqlite_Insert_Primary Key_Auto Increment - Fatal编程技术网

Python 如何插入到只包含一个具有自动增量主键的列的sqlite表中?

Python 如何插入到只包含一个具有自动增量主键的列的sqlite表中?,python,sqlite,insert,primary-key,auto-increment,Python,Sqlite,Insert,Primary Key,Auto Increment,我希望在sqlite中有一个“计数器”表,它总是给我一个新的唯一ID。首先,我创建下表: cursor.execute('''create table second (id integer primary key autoincrement, age integer)''') 然后执行以下命令序列: cursor.execute('''insert into second (age) values (1)''') cursor.lastrowid 每次执行上述两列时,我都会得到一个新的整数。

我希望在sqlite中有一个“计数器”表,它总是给我一个新的唯一ID。首先,我创建下表:

cursor.execute('''create table second (id integer primary key autoincrement, age integer)''')
然后执行以下命令序列:

cursor.execute('''insert into second (age) values (1)''')
cursor.lastrowid
每次执行上述两列时,我都会得到一个新的整数。这正是我所需要的。然而,上面的解决方案并不优雅,因为我使用了一个我并不真正需要的列(“年龄”)。我使用的原因如下。我可以创建一个只包含一个ID为的列的表:

cursor.execute('''create table first (id integer primary key autoincrement)''')
但是,问题是我无法插入到这个表中。以下操作不起作用:

cursor.execute('''insert into first () values ()''')
我收到以下错误消息:

sqlite3.OperationalError: near ")": syntax error
有人知道如何解决所描述的问题吗?

这应该可以:

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
这应该起作用:

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
报告说:

如果在insert上未指定ROWID,或者指定的ROWID值为NULL,则会自动创建相应的ROWID

因此,您可以显式指定NULL:

插入第一个(id)值(空)
或完全不指定值:

插入到第一个默认值中
上面写着:

如果在insert上未指定ROWID,或者指定的ROWID值为NULL,则会自动创建相应的ROWID

因此,您可以显式指定NULL:

插入第一个(id)值(空)
或完全不指定值:

插入到第一个默认值中
@thefourtheye From here:“如果在insert上未指定ROWID,或者指定的ROWID值为NULL,则会自动创建相应的ROWID。”@thefourtheye From here:“如果在insert上未指定ROWID,或者指定的ROWID值为NULL,则会自动创建相应的ROWID。”