使用" in"在带有参数的python里面的sql raw查询

时间:2014-05-29 05:13:19

标签: python mysql sql

我必须将多个id传递给我的sql raw查询,这些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 个答案:

答案 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]

答案 1 :(得分:0)

改编自引用的answer 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&替换它#39; 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]

答案 2 :(得分:-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]

Thanx全部用于您的反馈和宝贵的时间。