为什么Python sqlite3不插入自增ID

0 投票
1 回答
1668 浏览
提问于 2025-04-18 15:20

在Python 3.4.1中,为什么下面这个程序里的sqlite3没有把自动增加的ID插入到表里呢?根据SQLite的文档,一个整数主键列应该是自动增加的,我可以看到cur.lastrowid返回了一个有效的整数,但这个值却没有插入到表中(反而变成了NULL)。

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)

1 个回答

1

看来我之前误以为在SQLite中,'int'和'integer'是同一个意思。实际上,在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)

撰写回答