One way to recreate sequential numbering of your key is to drop the table and reconstruct it. Consider the renumber()
function in the code below:
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)
Result:
(1, u'one')
(2, u'two')
(3, u'three')
(4, u'four')
(2, u'two')
(4, u'four')
(1, u'two')
(2, u'four')