在Python 3.4.1中,为什么sqlite3不将自动递增的ID插入到下面程序的表中?根据{{3}},一个整数主键列应该自动递增,我可以看到cur.lastrowid返回一个有效的整数,但相同的值没有插入表中(它变为NULL)。 / p>
import sqlite3
with sqlite3.connect(':memory:') as conn:
cur = conn.cursor()
# Note that column 'id' is an integer primary key
cur.execute('create table test (id int primary key , name text)')
cur.execute('insert into test (name) values (?)', ('Test',))
last_id = cur.lastrowid
assert last_id is not None
id_, = cur.execute('select id from test').fetchone()
assert id_ == last_id, '{} != {}'.format(id_, last_id)
答案 0 :(得分:1)
显然,我错误地认为' int'是'整数'的同义词。在SQLite中。实际上,列are typeless in SQLite和integer primary key
是此规则的一个例外,有效地声明了一个自动递增的列:
import sqlite3
with sqlite3.connect(':memory:') as conn:
cur = conn.cursor()
# Note that column 'id' is an integer primary key
cur.execute('create table test (id integer primary key , name text)')
cur.execute('insert into test (name) values (?)', ('Test',))
last_id = cur.lastrowid
assert last_id is not None
id_, = cur.execute('select id from test').fetchone()
assert id_ == last_id, '{} != {}'.format(id_, last_id)