Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list in sql query as parameter [duplicate]

Tags:

python

sql

People also ask

How do you pass a list as a parameter in SQL query?

and then use setParameterList("ids", list) passing your list. Hibernate will do all the expansion for you! Show activity on this post. All you have to do is build the comma separated list of items and insert it in the string.

How do you pass a list of strings in SQL query in Python?

How to pass a python list of strings to SQL query such as select * from table where name in (names_from_python_list) where names_from_python_list is comma separated strings from python list? Doing ','. join(name for name in name_list) gives all the names in the list as a string i.e.

Can we use list in SQL?

You can create lists of SQL Query or Fixed Data values . In the Data Model components pane, click List of Values and then click Create new List of Values. Enter a Name for the list and select a Type.

How do you store SQL query results in a variable in Python?

First of all, c. fetchall() retrieves ALL the results from your query, we'll put them in a variable called rows . Then we create a iterator (the thing you tried to do with the while loop) by doing for row in rows . Then we simply print each row.


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)

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 !!!


The SQL you want is

select name from studens where id in (1, 5, 8)

If you want to construct this from the python you could use

l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'

The map function will transform the list into a list of strings that can be glued together by commas using the str.join method.

Alternatively:

l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'

if you prefer generator expressions to the map function.

UPDATE: S. Lott mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might want

select name from studens where id = 1 or id = 5 or id = 8

Generated by

sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))