Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)
edited by

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

select name from students where id = |IN THE LIST l|

How do I accomplish this?

1 Answer

0 votes
by (40.7k points)

Following is a variant using the parameterized query, this will work fine:

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)

Note: If you want to do it for strings then you'll get the escaping issue.

Browse Categories

...