重新創建密鑰的順序編號的一種方法是刪除表並重建它。考慮renumber()
功能在下面的代碼:
import sqlite3
from pprint import pprint
schema = '''
create table S (
id integer primary key autoincrement not null,
content text not null)'''
def init(db):
db.execute('drop table if exists S')
db.execute(schema)
db.execute('insert into S (content) VALUES ("one")')
db.execute('insert into S (content) VALUES ("two")')
db.execute('insert into S (content) VALUES ("three")')
db.execute('insert into S (content) VALUES ("four")')
db.commit()
def dump(db):
for row in db.execute('select * from S order by ID'):
print row
print
def renumber(db):
# To reorganize the primary key, create a new table
db.execute('create temp table temp_S as select content from S order by id')
db.execute('drop table S')
db.execute(schema)
db.execute('insert into S (content) '
' select content from temp_S order by rowid')
db.commit()
db = sqlite3.connect(':memory:')
init(db)
dump(db)
db.execute('delete from S where id in (1,3)')
db.commit()
dump(db)
renumber(db)
dump(db)
結果:
(1, u'one')
(2, u'two')
(3, u'three')
(4, u'four')
(2, u'two')
(4, u'four')
(1, u'two')
(2, u'four')
'計數(ID)'不受序列中的間隙。您認爲什麼是不更新較高ID的問題? –
相關:http://stackoverflow.com/questions/14023292/how-to-get-rownum-like-column-in-sqlite-iphone/19199219#19199219 –
我的問題是確切的事實,計數(id)不是受行ID影響。這很好,因爲這是我想要的,但我想知道如何更新表中所有更高ID的事件,所以ID將等於count(不存在id缺失),然後更新表序列。 – Artemis