如何在sqlite3中使用带有参数的IN运算符?

时间:2017-06-06 16:10:35

标签: python sqlite python-db-api

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的长度准备一系列参数持有者:

kludge(工作但丑陋)

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?我还没有设法在文档中找到一些东西。

0 个答案:

没有答案