Parameterization of queries "SELECT IN (...)"

I want to use MySQLdb to create a parameterized query, for example:

serials = ['0123456', '0123457']
c.execute('''select * from table where key in %s''', (serials,))

But in the end it turns out sending to the DBMS:

select * from table where key in ("'0123456'", "'0123457'")

Is it possible to create such a parameterized query? Or do I need to loop and create a result set?

Note: executeemany (...) will not work for this - it will return only the last result:

>>> c.executemany('''select * from table where key in (%s)''',
        [ (x,) for x in serials ] )
2L
>>> c.fetchall()
((1, '0123457', 'faketestdata'),)

The final solution, adapted from Gareth's clever answer:

# Assume check above for case where len(serials) == 0
query = '''select * from table where key in ({0})'''.format(
    ','.join(["%s"] * len(serials)))
c.execute(query, tuple(serials)) # tuple() for case where len == 1
+5
source share
1 answer

You want something like this, I think:

query = 'select * from table where key in (%s)' % ','.join('?' * len(serials))
c.execute(query, serials)
+3
source

All Articles