Python SQLite3 auto_increment 即使删除最大 ID 也会正确增加

Python SQLite3 auto_increment properly increase even when deleting the max ID

今天,

我开始使用 python 中的 SQL 数据库,我希望有多个 table,我可以在其中引用彼此 [=26= 中的行] 按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

来自SQLite Autoincrement

If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that changes the automatic ROWID assignment algorithm to prevent the reuse of ROWIDs over the lifetime of the database. In other words, the purpose of AUTOINCREMENT is to prevent the reuse of ROWIDs from previously deleted rows.

因此使用以下语句创建 table:

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

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

The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed.

选择权在你。