【问题标题】:Add an autoincrementing ID column to an existing table with Sqlite使用 Sqlite 将自动递增的 ID 列添加到现有表
【发布时间】:2016-04-25 23:18:17
【问题描述】:

使用 Sqlite,我想将一个自动递增的 ID 列添加到以前没有 ID 的现有表中:

import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()

c.execute('create table events (int weight, text str)')
c.execute('insert into events values(?, ?)', (1371, 'Test1'))
c.execute('insert into events values(?, ?)', (223, 'Test2'))
c.execute('select * from events'); print c.fetchall()
# [(1371, u'Test1'), (223, u'Test2')]

# add an autoincrementing ID to existing table
c.execute('alter table events add id int not null auto_increment primary key')

如何正确操作?我有这个错误:

sqlite3.OperationalError: 在“auto_increment”附近:语法错误

【问题讨论】:

    标签: python sql sqlite


    【解决方案1】:

    一旦创建 SQLite 表,就不能使用 alter table 对其进行重大修改。一个常见的流行建议是创建一个包含现有字段以及额外必填字段的新表,并将您的数据复制/导入到新表中,并可选择删除旧表。

    c.execute('create table events_copy(id integer primary key autoincrement, weight integer,str text)')
    c.execute('insert into events_copy(weight, str) select weight, str from events')
    c.execute('drop table events')
    c.execute('alter table events_copy rename to events')
    c.commit()
    

    【讨论】:

    • 如果表有大量行(如我的 > 100 万行)使用VACUUM 语句以摆脱缓存。
    • 请注意,sqlite 中的大多数表都会自动包含一个内部列rowid,它包含一个整数主键,这可能足以满足您的目的。 rowid 列对于表中的记录是唯一的(但如果记录被删除,可以重复使用)。更多信息:sqlite.org/lang_createtable.html#rowid
    【解决方案2】:

    这是一个简单的解决方案兄弟,只需使用“AUTOINCREMENT”而不是“AUTO_INCREMENT”

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 2016-07-23
      • 2016-05-29
      • 2019-01-18
      • 1970-01-01
      • 2020-09-01
      • 2015-06-05
      相关资源
      最近更新 更多