python - 使用 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])
我通过使用(用户,)而不是(用户)搜索并找到了这个解决方案。但我不知道它为什么起作用。有人可以启发我吗?谢谢!
解决方案
有效的原因(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'>
推荐阅读
- go - 从命名管道读取不会给出任何输出并无限期地阻塞代码
- kubernetes - 如何为 kubelet 指标配置 prometheus 目标
- python - TensorFlow KeyError Input_1
- php - PHP 中的抽象类 Lambda 函数
- graphql - 架构指令不按架构中指定的 LTR 顺序执行
- sql - SQL - 如何比较表和计数出现次数
- python - 用分隔符 / sep 分隔 csv 列
- delphi - Win32 CreateDirectory 失败,路径中有多个文件夹
- c# - Linq 查询以返回具有多个子数组的对象列表
- sql - PL/SQL 中的触发器