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:
query = '''select * from table where key in ({0})'''.format(
','.join(["%s"] * len(serials)))
c.execute(query, tuple(serials))
source
share