【发布时间】:2020-04-11 09:41:34
【问题描述】:
在 Python 中传递 SQL 查询的最佳做法是使用 (?) 占位符。我遇到了一个问题,我的 SQL 查询有一个 IN 表达式,并且无法确定如何将变量参数传递给占位符。 编辑:这与其他答案不同(如 cmets 中指出的那样),其他答案不包括拆包。我的工作代码是:
cursor = conn.cursor()
query = "Select touchtonekey, COUNT(touchtonekey) as touchedthismanytimes from vw_callhandlertraffic\
where callhandlername = ? and createddatetime between ?\
and ? and touchtonekey IN ('1','2') Group By touchtonekey Order by touchtonekey"
data = cursor.execute(query,'My CallHandler','2019-10-09 13:00:00',
'2019-12-09 13:59:59')
但是当我尝试使用此代码删除 IN 参数时:
query = "Select touchtonekey, COUNT(touchtonekey) as touchedthismanytimes from vw_callhandlertraffic\
where callhandlername = ? and createddatetime between ?\
and ? and touchtonekey IN ? Group By touchtonekey Order by touchtonekey"
data = cursor.execute(query,'My CallHandler','2019-10-09 13:00:00',
'2019-12-09 13:59:59', "('1','2')")
我明白了:
Right hand side of IN expression must be a COLLECTION type.
如果我从括号中删除引号,我会得到:
Invalid application buffer type. (-11116) (SQLBindParameter)
【问题讨论】:
-
这能回答你的问题吗? python list in sql query as parameter
-
具体来说,this 回答,您需要在其中创建占位符。请注意,某些 SQL 方言对 IN 子句中可以包含的参数数量有限制
-
哎呀,this 答案,甚至。他们基本上说同样的话。但实际上,他们缺少拆包
标签: python sql parameter-passing