[英]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.