我确信这已经被问过,并且之前已经回答过,但要么我是愚蠢的,要么就是没有一个答案适合我。也许我只是不理解它。但是,这是问题所在;我上了这堂课:
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.
>>>
答案 0 :(得分:4)
因为名称是可迭代的,所以它会尝试将其解压缩...将其放入一个仅用于修复的元组中
cur.execute("SELECT * FROM users WHERE name=?", (name,))