我写了下面的python-sqlite3代码。它有两个问题:
1.我想了解如何编写一个SQLite3语句来提取所有带有“cola”的行。.get_fav_drink_folks(drink) method
的正确语法是什么?
错误代码:
line 25, in get_fav_drink_folks self.cur.execute(sql, drink)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
脚本:
import sqlite3
class DB:
def __init__(self):
self.con = sqlite3.connect("database.db")
self.cur = self.con.cursor()
self.create_table()
def create_table(self):
table = """CREATE TABLE IF NOT EXISTS
database (name TEXT PRIMARY KEY,
fav_food TEXT,
fav_drink TEXT
)"""
self.cur.execute(table)
self.con.commit()
def insert_data_row(self, items):
sql = """INSERT OR IGNORE INTO database VALUES(?,?,?)"""
self.cur.execute(sql, items)
self.con.commit()
def get_fav_drink_folks(self, drink):
sql = """SELECT * FROM database WHERE fav_drink in (?)"""
self.cur.execute(sql, drink)
return self.cur.fetchmany()
if __name__ in "__main__":
db = DB()
data = [
("Mike", "Steak", "Cola",),
("Dora", "McDonalds", "Sprite",),
("Sally", "Salad", "Pepsi",),
("Eve", "Pizza", "Cola",),
]
for row_items in data:
print(f"{row_items=}")
db.insert_data_row(row_items)
print(f"\ncoke_drinkers are {db.get_fav_drink_folks('Cola')}")
1条答案
按热度按时间vhmi4jdf1#
1.您没有示例化该类。
db = DB
应为db = DB()
1.你给
get_fav_drink_folks
一个字符串,然后在self.cur.execute(sql, items)
上使用它你需要一个像其他函数一样的元组。
要么你
self.cur.execute(sql, (drink,))
要么你cola_drinkers = db.get_fav_drink_folks(('Cola',))
编辑:
对于元组逗号,请检查https://stackoverflow.com/a/57734760/5640517