【发布时间】:2016-03-21 19:54:34
【问题描述】:
我有一个整数元组,我想查询在元组中找到列值的所有行。构造查询很容易,但我希望它是 sql 注入证明。我通常使用准备好的语句,但我不知道如何处理这两种需求。
我的查询结构是这样的:
filterList = (1, 2, 4) #Taken as input. Should be integers
sqlRequest = 'SELECT * FROM table'
if filterList != None and len(filterList) > 0:
sqlRequest += ' WHERE column IN ('
addComa = False
for filter in filterList:
if addComa:
sqlRequest += ','
else:
addComa = True
sqlRequest += '%s'%(int(filter)) #casted to int to avoid SQL injection. Still not as good as I would like
sqlRequest += ')'
#At this point sqlRequest == 'SELECT * FROM table WHERE column IN (1,2,4)'
sqlResult = cursor.execute(sqlRequest)
我希望有一个更像的查询:
sqlRequest = 'SELECT * FROM table WHERE column IN (%s, %s, %s)'
并使用准备好的语句执行它:
sqlResult = cursor.execute(sqlRequest, filterList[0], filterList[1], filterList[2])
但 filterList 是可变长度的。有没有办法做类似的事情?
sqlResult = cursor.execute(sqlRequest, filterList) #where filterList is the whole tuple
【问题讨论】:
-
抱歉,我并不是要否定您建议的编辑,只是将其缩减为占位符乘法修复。
-
没问题。我必须进行至少 6 处更改(包括一些无用的更改)才能进行编辑。
标签: python mysql python-2.7 tuples