1

Python 3.5.2,标准库 sqlite3。

我正在尝试在子句中的IN运算符中使用动态标准发出 SQL 查询:WHERE

错误的代码(不起作用)

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

4

0 回答 0