Adapted from the answer Haim referenced, but for your particular case where you have nested lists:
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]
The reason why there's a %s
in the query string and not a %d
is because you're actually going to replace it with a bunch of %s
's (so %s
or %s,%s,%s
) in order to accommodate the variable number of id's you're trying to pass in.
So in your case, the first query string that would be built is:
"select branch_tag from builds where id in (6009)"
And the next one would be:
"select branch_tag from builds where id in (5989,5796,5793)"
This is all, of course, assuming that itlist
is meant to be nested as in your question. If it isn't, then most of this answer still applies as:
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]