使用Python和SQLite3动态生成SQL查询

rwo*_*lst 4 python sql sqlite

以下是我的问题的概括:

考虑一下表格

    ID    A    B    C
r1  1     1    0    1
.   .     .    .    .
.   .     .    .    .
.   .     .    .    .
rN  N     1    1    0
Run Code Online (Sandbox Code Playgroud)

A,B,C包含0或者1.我正在尝试编写一个python函数,它接受0's和1's 的排列列表,生成一个将传递给SQLite3的查询,然后计算A,B,C其中一个排列中的记录数.

例如,如果我将以下列表传递给我的函数permList = [[1,0,1],[1,0,0]],那么它会将所有[A,B,C]组合的记录计为[1,0,1]或者[1,0,0].

目前我这样做

def permCount(permList):
    SQLexpression = "SELECT Count(*) FROM Table WHERE "

    for i in range(len(permList)):
        perm = permList[i]
        SQLexpression += "(A=" + str(perm[0]) + " AND B=" + str(perm[1]) + 
                      " AND C=" + str(perm[2]) + ")"
        if i!=len(permList)-1:
            SQLexpression += " OR "

    *Execute SQLexpression and return answer*
Run Code Online (Sandbox Code Playgroud)

现在这很好,但它似乎有点小提琴.有没有更好的方法来动态生成输入长度permList未知的SQL查询?

unu*_*tbu 11

def permCount(permList):
    condition = ' OR '.join(['(A=? AND B=? AND C=?)' 
                             for row in permList])
    sql = "SELECT Count(*) FROM Table WHERE {c}".format(
        c=condition)
    args = sum(permList, [])
    cursor.execute(sql, args)
Run Code Online (Sandbox Code Playgroud)

使用参数化SQL.这意味着,而不是与字符串格式化插入值,使用地点标记(例如?),然后提供的参数作为所述第二参数cursor.execute.

这是更简单的代码并防止SQL注入.