Python/psycopg2在statemens中的位置

2024-05-19 21:14:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在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[…])”后出错。除了字符串操作之外,还有其他方法可以做到这一点吗?

谢谢


Tags: 方法from列表sqldata语句whereselect
3条回答

您可以直接使用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

要稍微解释一下答案并处理命名参数,并将列表转换为元组,请执行以下操作:

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.
})

对于IN运算符,需要tuple而不是list,并从SQL字符串中删除括号。

# using psycopg2
data=('UK','France')

sql='SELECT * from countries WHERE country IN %s'
cur.execute(sql,(data,))

在调试过程中,您可以检查是否使用

cur.mogrify(sql, (data,))

相关问题 更多 >