Python 3.5.2,stdlib sqlite3。
我尝试在IN
子句中的WHERE
运算符中使用动态条件发出SQL查询:
def top_item_counts_in_installations(cursor, installation_names):
return cursor.execute(
"SELECT itm.name, COUNT(*)"
" FROM Installations ins INNER JOIN Items itm ON itm.id=ins.itmid"
" WHERE ins.name IN (?)"
" GROUP BY itm.name"
" ORDER BY COUNT(*) DESC"
" LIMIT 3",
(installation_names,))
installation_names
是一个元组,但上面不起作用,很明显,错误
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
所以我目前所做的是根据installation_names
的长度准备一系列参数持有者:
def top_item_counts_in_installations(cursor, installation_names):
param_holders= ",".join("?" for i in installation_names)
return cursor.execute(
"SELECT itm.name, COUNT(*)"
" FROM Installations ins INNER JOIN Items itm ON itm.id=ins.itmid"
" WHERE ins.name IN (%s)"
" GROUP BY itm.name"
" ORDER BY COUNT(*) DESC"
" LIMIT 3" % param_holders,
installation_names)
是否有正确的方法来参数化IN
的正确术语而不是我的kludge?我还没有设法在文档中找到一些东西。