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

沃尔夫斯特

下面是我的问题的概括:

考虑表

    ID    A    B    C
r1  1     1    0    1
.   .     .    .    .
.   .     .    .    .
.   .     .    .    .
rN  N     1    1    0

A,B,C包含0或的地方1我正在尝试编写一个python函数,该函数接受一个0s和1s的排列列表,生成一个查询,该查询将传递给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*

现在这很好,但似乎有点摆弄。有没有更好的方法可以动态生成输入长度permList未知的SQL查询

算了吧
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)

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章