使用variab查询Sqlite数据库

2024-06-14 12:02:43 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试学习Sqlite,但我不确定自己是否理解为什么无法使此代码正常工作:

def get_bday(self):
    name = self.input_name()
    self.c.execute('SELECT * FROM birthdays WHERE name =?', name)
    for row in self.c.fetchall():
        print(row)

正在从另一个方法返回name变量。对于这个例子,我使用不带引号的“JoeSmoe”作为name变量来执行查询。当我运行上述代码时,我得到:

self.c.execute('SELECT * FROM birthdays WHERE name =?', name)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.

如果你计算空间,“joe smoe”这个词有8个绑定长度。但我不知道那是什么意思。我假设我可以简单地将一个变量直接传递给Sqlite,就像在Python中传递变量一样简单,但事实并非如此。我想这与我对元组的理解很差有关


Tags: 代码namefromselfinputexecutesqliteget
1条回答
网友
1楼 · 发布于 2024-06-14 12:02:43

SQLite目前认为您需要查询'joe smoe'的每个字母

要避免这种情况,只需将name放入某种容器中:元组或列表,例如:

def get_bday(self):
    name = self.input_name()
    self.c.execute('SELECT * FROM birthdays WHERE name =?', (name,))
    #                                                       ^    ^^
    for row in self.c.fetchall():
        print(row)

相关问题 更多 >