Python/psycopg2 WHERE IN statement

陌路散爱 提交于 2019-11-27 20:16:23

问题


What is the correct method to have the list (countryList) be available via %s in the SQL statement?

# using psycopg2
countryList=['UK','France']

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

As it is now, it errors out after trying to run "WHERE country in (ARRAY[...])". Is there a way to do this other than through string manipulation?

Thanks


回答1:


For the IN operator, you want a tuple instead of list, and remove parentheses from the SQL string.

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

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

During debugging you can check that the SQL is built correctly with

cur.mogrify(sql, (data,))



回答2:


To expland on the answer a little and to address named parameters, and converting lists to tuples:

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



回答3:


You could use a python list directly as below. It acts like the IN operator in SQL and also handles a blank list without throwing any error.

data=['UK','France']
sql='SELECT * from countries WHERE country = ANY (%s)'
cur.execute(sql,(data,))

source: http://initd.org/psycopg/docs/usage.html#lists-adaptation



来源:https://stackoverflow.com/questions/28117576/python-psycopg2-where-in-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!