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')"
-
1bobby-tables.com/pythonPatrick Artner– Patrick Artner2020年04月01日 20:22:42 +00:00Commented Apr 1, 2020 at 20:22
-
Dont use format to format the query. Use parametrized queries and supply a tuple of values for your querystring with placeholdeers inside it.Patrick Artner– Patrick Artner2020年04月01日 20:23:34 +00:00Commented Apr 1, 2020 at 20:23
1 Answer 1
You're missing the quotes around each element:
sList = ','.join('\'' + i + '\'' for i in myList)
answered Apr 1, 2020 at 20:23
Mureinik
316k54 gold badges404 silver badges406 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default