[英]Dynamically Generating SQL Queries with Python and SQLite3
以下是我的问题的概括:
考虑一下表格
ID A B C
r1 1 1 0 1
. . . . .
. . . . .
. . . . .
rN N 1 1 0
列A,B,C
包含0
或1
。 我正在尝试编写一个python函数,它接受0
和1
的排列列表,生成一个将传递给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*
现在这很好,但它似乎有点小提琴。 有没有更好的方法来动态生成SQL查询,其中输入permList
的长度未知?
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 。 这意味着不是使用字符串格式插入值,而是使用placemarkers(例如?
),然后将参数作为cursor.execute
的第二个参数提供。
这是更简单的代码并防止SQL注入 。
在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 "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.