0

I have a list with strings:

list = ['abc', 'cbd', 'bdc']

I want to use it as an input within an SQL query like:

query=('SELECT * from table where column1 in list')

What is the best way to do it in order for the SQL to run for these 3 items of the list?

Tot Zam
  • 8,406
  • 10
  • 51
  • 76
Alexis
  • 25
  • 4
  • 1
    Possible duplicate of [python list in sql query as parameter](https://stackoverflow.com/questions/283645/python-list-in-sql-query-as-parameter) – DannyMoshe Mar 20 '19 at 15:54

2 Answers2

2

It is generally a bad idea to generate SQL text like this (this is a brief explanation why). Common database access libraries will do the query parameter substitution for you (psycopg for PostgreSQL and MySQLdb for MySQL both do this, not sure about others).

That said, if you are very-very sure that the values you pass in the array are safe, you could do something like

my_list =['abc', 'cbd', 'bdc'] # do not call your variable list, list is a type
query = 'SELECT * from table where column1 in {}'.format(tuple(my_list))
Mad Wombat
  • 14,490
  • 14
  • 73
  • 109
0

First, you could transform the list in a string and then you can add it to your query:

My_list =['abc', 'cbd', 'bdc']
slist=" '"
for i in My_list:
      slist+= i.strip()+"', '"
slist=slist[:-3]
query='''SELECT * from table where column1 in (%s)'''%slist
Nate
  • 856
  • 6
  • 5