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

时间:2013-09-07 14:35:10

标签: python sql sqlite

以下是我的问题的概括:

考虑表

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

A,B,C包含01的位置。我正在尝试编写一个python函数,它接受01的排列列表,生成一个将传递给SQLite3的查询,然后计算具有{{的记录数。 1}}在其中一种排列中。

例如,如果我将以下列表传递给我的函数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* 的长度未知的SQL查询?

2 个答案:

答案 0 :(得分: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)

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

这是更简单的代码并阻止了SQL injection

答案 1 :(得分:1)

在main for循环中尝试这些更改,以使用pythons生成器和列表推导功能。

def permCount(permList):

SQLexpression = "SELECT Count(*) FROM Table WHERE "

for perm in permList:    # if you need the i for other reason, you could write:
                         # for i, perm in enumerate(permList)

    a, b, c = [str(_) for _ in perm]

    SQLexpression += "(A=" + a + " AND B=" + b + \
                  " AND C=" + c + ") OR "

SQLexpression = SQLexpression[:-4] + ";"   # Trim the last " OR "
相关问题