Executing “SELECT … WHERE … IN …” using MySQLdb

Unfortunately, you need to manually construct the query parameters, because as far as I know, there is no built-in bind method for binding a list to an IN clause, similar to Hibernate’s setParameterList(). However, you can accomplish the same with the following:

Python 3:

args=['A', 'C']
sql="SELECT fooid FROM foo WHERE bar IN (%s)" 
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
cursor.execute(sql, args)

Python 2:

args=['A', 'C']
sql="SELECT fooid FROM foo WHERE bar IN (%s)" 
in_p=', '.join(map(lambda x: '%s', args))
sql = sql % in_p
cursor.execute(sql, args)

Leave a Comment