插入id 1和2.删除id 2.插入新行,它获取id 2而不是3.如何更改?我不想重用主键。
import sqlite3, os
os.remove('mydatabase.db')
conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM
cursor = conn.cursor()
# create a table
cursor.execute("CREATE TABLE if not exists albums (id INTEGER PRIMARY KEY NOT NULL, title text, artist text, release_date text, publisher text, media_type text)")
cursor.execute("CREATE TABLE if not exists anti (id INTEGER, title text, artist text, release_date text, publisher text, media_type text)")
conn.commit()
cursor.execute("INSERT INTO albums VALUES (null, 'Glow', 'Andy Hunter', '7/24/2012', 'Xplore Records', 'MP3')")
cursor.execute("INSERT INTO albums VALUES (null, 'second', 'artist', '7/24/2012', 'Xplore Records', 'MP3')")
conn.commit()
cursor.execute("SELECT * FROM albums")
print(cursor.fetchall())
cursor.execute("INSERT INTO anti SELECT * FROM albums WHERE title='second'")
cursor.execute("DELETE FROM albums WHERE title='second'")
cursor.execute("INSERT INTO albums VALUES (null, 'third', 'artist', '7/24/2012', 'Xplore Records', 'MP3')")
conn.commit()
cursor.execute("SELECT * FROM albums")
print(cursor.fetchall())
cursor.execute("SELECT * FROM anti")
print(cursor.fetchall())
答案 0 :(得分:4)
来自https://www.sqlite.org/autoinc.html:
如果AUTOINCREMENT关键字出现在INTEGER PRIMARY KEY之后,则会更改自动ROWID分配算法,以防止在数据库的生命周期内重用ROWID。换句话说,AUTOINCREMENT的目的是防止从以前删除的行重用ROWID。