通过 SQL 语句中的 %s 获取列表 (countryList) 的正确方法是什么?
# using psycopg2
countryList=['UK','France']
sql='SELECT * from countries WHERE country IN (%s)'
data=[countryList]
cur.execute(sql,data)
就像现在一样,尝试运行“WHERE country in (ARRAY[...])”后会出错。除了通过字符串操作之外,还有其他方法可以做到这一点吗?
谢谢
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.
})
'row_factory': dict_row
,以下内容对我有用:SQL:
... where col_name = ANY(%(col_name)s);
connection.execute(sql, {'col_name': ['xx',...,'yy']})