【问题标题】:Why doesn't Python sqlite3 insert auto-incremented ID为什么 Python sqlite3 不插入自增 ID
【发布时间】:2014-09-22 02:11:09
【问题描述】:

在 Python 3.4.1 中,为什么sqlite3 不将自动递增的 ID 插入到下面程序的表中?根据the SQLite documentation,整数主键列应该自动递增,我可以从 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)

【问题讨论】:

    标签: python python-3.x sqlite


    【解决方案1】:

    显然,我错误地认为“int”是 SQLite 中“整数”的同义词。事实上,列are typeless in SQLiteinteger 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)
    

    【讨论】:

    • 这不是错误;文档明确说明您需要使用INTEGER PRIMARY KEY
    • 官方类型名称为INTEGER,其他名称仅创建一个type affinity
    • @MartijnPieters 是的,你说得对,与此同时,我能够挖掘到更多信息。直到现在才意识到 SQLite 的无类型。谢谢!
    猜你喜欢
    • 2023-01-21
    • 2012-04-25
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多