[英]How to insert into sql query string with a string derived from python list
I have an example SQL query string like this:我有一个像这样的示例 SQL 查询字符串:
query = "select * from myTbl where name in ('apple', 'pear')"
I need to replace ('apple', 'pear')
with any python list generated.我需要用生成的任何 python 列表替换
('apple', 'pear')
。
How I can insert any list into the SQL query string without hardcoded in. The code below does not work:如何在没有硬编码的情况下将任何列表插入到 SQL 查询字符串中。 下面的代码不起作用:
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')"
它给出了一个查询字符串
'select * from myTbl where name in (apple,pear)'
我需要的是一个查询字符串"select * from myTbl where name in ('apple','pear')"
您缺少每个元素周围的引号:
sList = ','.join('\'' + i + '\'' for i in myList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.