【问题标题】:Python SQLite3 auto_increment properly increase even when deleting the max ID即使删除最大 ID,Python SQLite3 auto_increment 也会正确增加
【发布时间】:2020-07-16 18:51:47
【问题描述】:

生日,

我开始在 python 中使用 SQL 数据库,我想要多个表,我可以在其中通过 ID 引用彼此表中的行。因此,我使用的是“testID integer PRIMARY KEY”列。

列的值根据需要增加,但如果我删除具有最大 ID 的行然后添加另一个条目,它将收到之前已经设置的 ID。这很有效,因为删除最近的行会导致列中的最大 ID 变小,这对我来说很有意义。

我现在想知道,有没有办法让数据库记住之前设置的每个 ID,而不是将相同的 ID 设置两次,即使从数据库中删除了最大 ID?

MWE 可能会更清楚:

conn = sqlite3.connect("db_problem.db")
c = conn.cursor()
with conn:
    c.execute("CREATE TABLE test ("
              "testID integer PRIMARY KEY, "
              "col1 integer)")
    c.execute("INSERT INTO test (col1) VALUES (1)")
    c.execute("INSERT INTO test (col1) VALUES (2)")
    c.execute("DELETE FROM test WHERE col1 LIKE 1")
    c.execute("SELECT testID FROM test WHERE col1 LIKE 2")
    print(c.fetchall()) # this stays 2, even tho there is only one row left, which works fine
    c.execute("INSERT INTO test (col1) VALUES (3)")
    c.execute("DELETE FROM test WHERE col1 LIKE 3")
    c.execute("INSERT INTO test (col1) VALUES (4)")
    c.execute("SELECT testID FROM test WHERE col1 LIKE 4")
    print(c.fetchall()) # Here the autoincrement was set to 3 although it is the fourth entry made

【问题讨论】:

    标签: python sqlite primary-key auto-increment


    【解决方案1】:

    来自SQLite Autoincrement

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

    所以用这个语句创建表:

    c.execute("CREATE TABLE test ("
              "testID integer PRIMARY KEY AUTOINCREMENT , "
              "col1 integer)")
    

    但是您必须考虑文档的另一部分:

    AUTOINCREMENT 关键字强加了额外的 CPU、内存、磁盘空间和 磁盘 I/O 开销,如果不是严格需要,应避免使用。

    选择权在你。

    【讨论】:

    • 确实,我的数据库搞混了,SQLite3 FAQ 在第一个条目中涵盖了这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2017-12-13
    • 2020-01-12
    • 1970-01-01
    相关资源
    最近更新 更多