通过SQL语句中的%s提供列表(countryList)的正确方法是什么?
# using psycopg2
countryList=['UK','France']
sql='SELECT * from countries WHERE country IN (%s)'
data=[countryList]
cur.execute(sql,data)
现在,尝试运行“(ARRAY [...])所在的国家/地区”后,它会出错。除了通过字符串操作之外,还有其他方法吗?
谢谢
Answers:
为了稍微解释答案并解决命名参数,并将列表转换为元组:
countryList = ['UK', 'France']
sql = 'SELECT * from countries WHERE country IN %(countryList)s'
cur.execute(sql, { # You can pass a dict for named parameters rather than a tuple. Makes debugging hella easier.
'countryList': tuple(countryList), # Converts the list to a tuple.
})
cur.execute("SELECT * FROM table WHERE col IN %(list1)s OR col IN %(list2)s", {'list1': tuple(1,2,3), 'list2' = tuple(4,5,6)})
您可以直接使用python列表,如下所示。它的行为类似于SQL中的IN运算符,还可以处理空白列表而不会引发任何错误。
data=['UK','France']
sql='SELECT * from countries WHERE country = ANY (%s)'
cur.execute(sql,(data,))
来源:http : //initd.org/psycopg/docs/usage.html#lists-adaptation
cur.execute(sql, (tuple(data),))