【问题标题】:Don't use deleted primary keys不要使用已删除的主键
【发布时间】:2016-09-14 01:44:24
【问题描述】:

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

【问题讨论】:

    标签: python sqlite primary-key


    【解决方案1】:

    来自https://www.sqlite.org/autoinc.html

    如果 AUTOINCREMENT 关键字出现在 INTEGER PRIMARY KEY 之后,则会更改自动 ROWID 分配算法,以防止在数据库的生命周期内重复使用 ROWID。换句话说,AUTOINCREMENT 的目的是防止重复使用以前删除的行中的 ROWID。

    【讨论】:

    • 这个问题值得关注吗?我没有看到任何重复的
    • 是的,我想是的。而且我认为如果问题是重复的,你不应该觉得你需要删除它。问题不断作为重复而关闭,但不会被删除。如果有重复,这里的措辞可能对搜索引擎更友好。
    • @user193661 你很幸运; other question 不太通用。
    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 2020-10-24
    • 1970-01-01
    • 2013-11-04
    • 2017-03-10
    • 2012-11-30
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多