python list in sql query as parameter [duplicate] python list in sql query as parameter [duplicate] python python

python list in sql query as parameter [duplicate]


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)' % placeholderscursor.execute(query, l)


Easiest way is to turn the list to tuple first

t = tuple(l)query = "select name from studens where id IN {}".format(t)


Dont complicate it, Solution for this is simple.

l = [1,5,8]l = tuple(l)params = {'l': l}cursor.execute('SELECT * FROM table where id in %(l)s',params)

enter image description here

I hope this helped !!!