Skip to content
Advertisement

How to insert into sql query string with a string derived from python list

I have an example SQL query string like this:

query = "select * from myTbl where name in ('apple', 'pear')"

I need to replace ('apple', 'pear') with any python list generated.

How I can insert any list into the SQL query string without hardcoded in. The code below does not work:

myList = ['apple', 'pear']
sList = ','.join(myList)
"select * from myTbl where name in ({})".format(sList)

It gives a query string 'select * from myTbl where name in (apple,pear)' What I need is a query string "select * from myTbl where name in ('apple','pear')"

Advertisement

Answer

You’re missing the quotes around each element:

sList = ','.join(''' + i + ''' for i in myList)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement