gpt4 book ai didi

关于提供的绑定(bind)数量的 Python sqlite3 错误

转载 作者:搜寻专家 更新时间:2023-10-30 20:11:10 24 4
gpt4 key购买 nike

我确定之前已经有人问过并回答过这个问题,但要么我很愚蠢,要么没有一个答案对我有用。也许我只是不明白。但是,这就是问题所在;我得到了这门课:

import sqlite3

class User:
def __init__(self, name, age):
self.name = name
self.age = age



def saveToDatabase(self):
connection = sqlite3.connect("users.db")
cur = connection.cursor()

cur.execute("DROP TABLE IF EXISTS users")
cur.execute("CREATE TABLE users (name TEXT PRIMARY KEY, age INTEGER)")
cur.execute("INSERT OR REPLACE INTO users VALUES (?,?)", (self.name, self.age))

connection.commit()
connection.close()

@staticmethod
def printUserFromDatabase(name):
connection = sqlite3.connect("users.db")
cur = connection.cursor()

cur.execute("SELECT * FROM users WHERE name=?", name)
print(cur.fetchone())

connection.close()

它起作用了,创建了数据库,我可以向其中添加用户,但是每当我尝试从数据库中打印用户时,就会发生这种情况:

>>> tom = User("Tom", 24)
>>> tom.saveToDatabase()
>>> User.printUserFromDatabase("Tom")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
User.printUserFromDatabase("Tom")
File "C:\Users\Markus\Desktop\foo\foo.py", line 25, in printUserFromDatabase
cur.execute("SELECT * FROM users WHERE name=?", name)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.
>>>

最佳答案

因为 name 是可迭代的,所以它试图解压它......把它放在一个只有自己修复的元组中

cur.execute("SELECT * FROM users WHERE name=?", (name,))

关于关于提供的绑定(bind)数量的 Python sqlite3 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12626706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com