give parameter(list or array) to in operator - python, sql

Batuhan B picture Batuhan B · Jan 11, 2015 · Viewed 12.1k times · Source

I have a list in python.

article_ids = [1,2,3,4,5,6]

I need to use this list in sql statement like this :

SELECT id FROM table WHERE article_id IN (article_ids)

How can I provide this list to my IN() clause?

I have already try some ways which I googled, but I couldn't figure it out.

>> print ids_list
    placeholders= ', '.join('?'*len(ids_list))  # "?, ?, ?, ... ?"
    query = 'SELECT article_id FROM article_author_institution WHERE institution_id IN ({})'.format(placeholders)
    print query
    cursor.execute(query, ids_list)

Error message I get:

SELECT article_id FROM article_author_institution WHERE institution_id IN (?)
     query = query % db.literal(args)
    TypeError: not all arguments converted during string formatting

For example for:

ids_list = [9,10]

placeholders= ', '.join('%'*len(ids_list))  # "?, ?, ?, ... ?"
query = 'SELECT aid FROM article_author_institution WHERE instid IN ({})'.format(placeholders)
print query
cursor.execute(query, ids_list)

The output and error message are:

SELECT aid FROM article_author_institution WHERE instid IN (%, %)
Traceback (most recent call last):
  File "deneme3.py", line 11, in <module>
    cursor.execute(query, ids_list)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute
    query = query % db.literal(args)
ValueError: unsupported format character ',' (0x2c) at index 61

Answer

elyase picture elyase · Jan 11, 2015

The idea is to have a query like this one:

cursor.execute("SELECT ... IN (%s, %s, %s)", (1, 2, 3))

where each %s will be substituted by elements in your list. To construct this string query you can do:

placeholders= ', '.join(['%s']*len(article_ids))  # "%s, %s, %s, ... %s"
query = 'SELECT name FROM table WHERE article_id IN ({})'.format(placeholders)

finally

cursor.execute(query, tuple(article_ids))