我敢肯定这已经被问过,并且以前回答过,但是要么我很愚蠢,要么没有一个答案对我有用。也许我只是不明白。但是,这就是问题所在;我得到了这个类:
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.
>>>