在Python3的sqlite3中,lastrowid返回None

在Python3的sqlite3中,lastrowid返回None,python,sqlite,Python,Sqlite,在使用Python从SQLite3中的查询中检索最后一个插入id时遇到了一个问题,在尝试修复这个问题时遇到了一些麻烦。 以下是我的代码示例: import sqlite3 # Setup our SQLite Database conn = sqlite3.connect('value_serve.db') conn.execute("PRAGMA foreign_keys = 1") # Enable Foreign Keys cursor = conn.cursor() # Create

在使用Python从SQLite3中的查询中检索最后一个插入id时遇到了一个问题,在尝试修复这个问题时遇到了一些麻烦。 以下是我的代码示例:

import sqlite3

# Setup our SQLite Database
conn = sqlite3.connect('value_serve.db')
conn.execute("PRAGMA foreign_keys = 1") # Enable Foreign Keys
cursor = conn.cursor()

# Create table for Categories
conn.executescript('DROP TABLE IF EXISTS Category;')
conn.execute('''CREATE TABLE    Category (
                id              INTEGER PRIMARY KEY AUTOINCREMENT,
                category        CHAR(132),
                description     TEXT,
                parent_id       INT,
                FOREIGN KEY     (parent_id) REFERENCES Category (id)
                );''')

conn.execute("INSERT INTO Category (category, parent_id) VALUES ('Food', NULL)")
food_category = cursor.lastrowid
conn.execute("INSERT INTO Category (category, parent_id) VALUES ('Beverage', NULL)")
beverage_category = cursor.lastrowid
...
conn.commit()  # Commit to Database
无论我做什么,当我试图获得“食品类别”的值时,我得到的返回值是“无”


任何帮助都将不胜感激,提前谢谢

为每个光标设置
lastrowid
值,并且仅对该光标可见

您需要在执行查询的游标上执行查询以获取最后一行id。您请求的是任意游标,一个从未实际用于执行最后一行id查询的游标,但该游标无法知道该值

如果您实际在
游标上执行查询
对象,它将起作用:

cursor.execute("INSERT INTO Category (category, parent_id) VALUES ('Food', NULL)")
food_category = cursor.lastrowid
connection.execute()
函数为该查询创建一个新的(本地)游标,最后一行id仅在该本地游标上可见。当您使用
connection.execute()
时,将返回该光标,因此您可以从该返回值中获得相同的值:

cursor_used = conn.execute("INSERT INTO Category (category, parent_id) VALUES ('Food', NULL)")
food_category = cursor_used.lastrowid