2016-05-17 10 views
2

id 1と2を挿入します。2. idを削除します。2.新しい行を挿入すると、3ではなくid 2が取得されます。私は主キーを再利用したくありません。削除された主キーは使用しないでください

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()) 

答えて

3

https://www.sqlite.org/autoinc.htmlから:

AUTOINCREMENTキーワードは、データベースの寿命にわたってのROWIDの再使用を防止するための自動ROWIDの割り当てアルゴリズムを変更INTEGER PRIMARY KEY、後に表示された場合。つまり、AUTOINCREMENTの目的は、以前に削除された行からROWIDを再利用しないようにすることです。

+0

この質問は続ける価値がありますか?私は重複を見たことがない – user193661

+0

はい、私はそうだと思います。そして、私はそれが重複している場合、質問を削除する必要があると感じるはずはないと思います。質問は常に重複として閉じられますが、削除されることはありません。重複があった場合は、多分ここでの言葉遣いが検索エンジンにやさしくなります。 –

+1

@ user193661あなたは幸運を得ました。 [その他の質問](http://stackoverflow.com/questions/33135324/sqlite-prevent-primary-key-value-from-resetting-after-delete-all-rows?lq=1)はあまり一般的ではありませんでした。 –

関連する問題