我相信这是被问过的,以前也有人回答过,但要么我很傻,要么就没有一个答案对我有用。也许我就是不明白。但问题是,我上了这门课:

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是iterable,所以它试图将其解包…把它放在一个元组中,只需自己修复

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

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

10-09 03:41