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

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.