使用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": 语法错误
VACUUM
语句来清除缓存。 - Ivan Talalaevrowid
的内部列,它保存着整数主键,很可能已经足够满足您的需求。rowid
列对于表中的记录是唯一的(但如果记录被删除,它可能会被重用)。更多信息请参考:https://sqlite.org/lang_createtable.html#rowid - Inti