[英]Conditional query with 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:参数的类型不受支持
def splitbill(user):
row = c.execute('SELECT * FROM database WHERE user = (?) ORDER BY datetime DESC LIMIT 1', (user,)).fetchall()
print(row[0])
我用(user,)而不是(user)进行了搜索,并找到了这种解决方案。 但是我不知道为什么它起作用。 有人可以启发我吗? 谢谢!
(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'>
(user)被解释为一个表达式,而(user,)始终是一个元组。
在Python世界中,单元素tuples
被宣布有,
在年底。 例如:
>>> p=(1)
>>> print(type(p))
<type 'int'> #--note that this is taken as an int, irrespective of the braces.
>>> q=(1,)
>>> print(type(q))
<type 'tuple'>
函数c.excute
可能接受一个占位符tuple
,这就是为什么您传入的(user)
参数不被视为元组的原因。 很好的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.