python list in sql query as parameter

后端 未结 15 1764
耶瑟儿~
耶瑟儿~ 2020-11-22 09:39

I have a python list, say l

l = [1,5,8]

I want to write a sql query to get the data for all the elements of the list, say

s         


        
15条回答
  •  天命终不由人
    2020-11-22 09:45

    Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.

    Here's a variant using a parameterised query that would work for both:

    placeholder= '?' # For SQLite. See DBAPI paramstyle.
    placeholders= ', '.join(placeholder for unused in l)
    query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
    cursor.execute(query, l)
    

提交回复
热议问题