在Python中使用参数的SQL原生查询中的“in”
我需要把多个ID传递给我的SQL原始查询,这些ID会作为参数传入。
我现在是这样做的:
itlist=[6009,[5989,5796,5793],5788,5750]
for it in itlist:
cursor.execute("select branch_tag from builds where id in (%d);"%[it])
data1=cursor.fetchall()
for record in data1:
print record[0]
但是这样会出现错误,我不知道怎么把这个列表传递给SQL查询。
如果能帮忙解决这个问题,我会非常感激...提前谢谢你!
3 个回答
-1
把每个元素都转换成一个列表,然后就可以用Python的基本方法来处理,具体做法如下:
itlist=[[6009],[5989,5796,5793],[5750]]
for it in itlist:
cursor.execute("select branch_tag from builds where id=(select max(id) from builds where id in ("+ str(it)[1:-1] +"));")
data1=cursor.fetchall()
for record in data1:
print record[0]
感谢大家的反馈和宝贵时间。
0
把这个列表压扁成一个新的列表,然后把这个新列表传给你的查询:
def flatten(foo):
newl = []
for x in foo:
if hasattr(x, '__iter__'):
for y in flatten(x):
newl.append(y)
else:
newl.append(x)
return newl
itlist=[6009,[5989,5796,5793],5788,5750]
newitlist = flatten(itlist)
for it in newitlist:
cursor.execute("select branch_tag from builds where id in (%d);"%[it])
data1=cursor.fetchall()
for record in data1:
print record[0]
0
这段内容是根据Haim提到的一个回答改编的,特别适合你这种有嵌套列表的情况:
itlist=[6009,[5989,5796,5793],5788,5750]
for it in itlist:
# This ensures that 'it' is a list even if it is just a single element
if type(it) != list:
it = [it]
format_strings = ','.join(['%s'] * len(it))
cursor.execute("select branch_tag from builds where id in (%s)" % format_strings,
tuple(it))
data1=cursor.fetchall()
for record in data1:
print record[0]
在查询字符串中出现的%s
而不是%d
的原因是,因为你实际上要用一堆%s
来替换它(比如%s
或者%s,%s,%s
),这样才能处理你想传入的可变数量的id。
所以在你的情况下,构建的第一个查询字符串是:
"select branch_tag from builds where id in (6009)"
接下来会是:
"select branch_tag from builds where id in (5989,5796,5793)"
当然,这一切都是假设itlist
是像你问题中那样嵌套的。如果不是的话,大部分内容仍然适用,如下:
itlist=[6009,5989,5796,5793,5788,5750]
format_strings = ','.join(['%s'] * len(itlist))
cursor.execute("select branch_tag from builds where id in (%s)" % format_strings,
tuple(itlist))
data1=cursor.fetchall()
for record in data1:
print record[0]