0

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')"

Mureinik
316k54 gold badges404 silver badges406 bronze badges
asked Apr 1, 2020 at 20:21
2
  • 1
    bobby-tables.com/python Commented 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. Commented Apr 1, 2020 at 20:23

1 Answer 1

1

You're missing the quotes around each element:

sList = ','.join('\'' + i + '\'' for i in myList)
answered Apr 1, 2020 at 20:23
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.