在现有的Sqlite表中添加一个自增ID列

7
使用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: near "auto_increment": 语法错误

2个回答

18

一旦创建了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语句来清除缓存。 - Ivan Talalaev
5
请注意,sqlite 中的大多数表格都会自动包含一个名为 rowid 的内部列,它保存着整数主键,很可能已经足够满足您的需求。rowid 列对于表中的记录是唯一的(但如果记录被删除,它可能会被重用)。更多信息请参考:https://sqlite.org/lang_createtable.html#rowid - Inti

-3

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接