首页 > 解决方案 > 使用 sqlite3 python 进行条件查询

问题描述

此代码片段是我目前正在开发的电报机器人的一部分。我使用了 PyTelegramBotAPI 包并使用 @bot.callback_query_handler() 来处理来自用户的回调查询。然后,我创建了一个函数,该函数使用以下代码从数据库中为该特定用户打印最后一个条目:

def splitbill(user):
    row = c.execute('SELECT * FROM database WHERE user = (?) ORDER BY datetime DESC LIMIT 1', user).fetchall()
    print(row[0])

此返回的错误说明 ValueError: parameters are of unsupported type

def splitbill(user):
    row = c.execute('SELECT * FROM database WHERE user = (?) ORDER BY datetime DESC LIMIT 1', (user,)).fetchall()
    print(row[0])

我通过使用(用户,)而不是(用户)搜索并找到了这个解决方案。但我不知道它为什么起作用。有人可以启发我吗?谢谢!

标签: pythonsqlitetelegram-bot

解决方案


有效的原因(user,)是该execute方法需要一个元组,并且当您(user)不带逗号通过时,python 将其解释为user.

您可以在 python shell 中快速验证这一点:

>>> a = 'howdy'
>>> tuple = (a, )      # note the comma
>>> not_a_tuple = (a)  # note the lack of comma
>>>
>>> print(tuple)       
('howdy',)
>>> print(not_a_tuple)
howdy
>>>
>>> type(tuple)
<class 'tuple'>
>>> type(not_a_tuple)
<class 'str'>

推荐阅读