错误:sqlite3。ProgrammingError:提供的绑定数量不正确。当前语句使用1,而提供了5。
import sqlite3
connection = sqlite3.connect('collyers_car_park.db')
cursor = connection.cursor()
# create details table
details_table = """CREATE TABLE IF NOT EXISTS
details(
user_id INTEGER PRIMARY KEY,
)"""
details_default_values = [
(1),
(2),
(3),
(4),
(5)
]
cursor.executemany("INSERT INTO details (user_id) VALUES (?)", [details_default_values])
connection.commit()
latest_id = cursor.execute("""SELECT * FROM details WHERE user_id = (SELECT MAX(user_id)) FROM details""")
print(latest_id)
抛出错误The current statement uses 1, and there are 5 supplied.
,因为details_default_values已经是一个列表,并且您在行cursor.executemany("INSERT INTO details (user_id) VALUES (?)", [details_default_values])
中包装另一个列表,导致第一次插入包含5个值而不是1。
然而,另一个下面的错误:因为代码使用单值元组,你需要把每个元组里面有一个逗号,像这样(1,)
下面的代码几乎与您的相同,并运行。请注意,我调整了代码中的一些其他部分,因为它不会运行,所以其他部分与您的代码略有不同。张贴了我的调整,以提供一个成功运行的示例:)
import sqlite3
connection = sqlite3.connect('collyers_car_park.db')
cursor = connection.cursor()
# create details table
details_table = """CREATE TABLE IF NOT EXISTS
details(
user_id INTEGER PRIMARY KEY
);"""
cursor.execute(details_table)
details_default_values = [(1,),(2,),(3,),(4,),(5,)] # <---- single value tuples
cursor.executemany("INSERT INTO details (user_id) VALUES (?)", details_default_values)
connection.commit()
latest_id = cursor.execute("""SELECT * FROM details""")
print(latest_id.fetchall())