【问题标题】:Python/psycopg2 WHERE IN statementPython/psycopg2 WHERE IN 语句
【发布时间】:2015-03-22 22:40:45
【问题描述】:

在 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[...])”后出错。除了通过字符串操作之外,还有其他方法吗?

谢谢

【问题讨论】:

    标签: python psycopg2 where-in


    【解决方案1】:

    您可以直接使用 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),))
    【解决方案2】:

    稍微解释一下答案并解决命名参数,并将列表转换为元组:

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

    【讨论】:

    • 感谢您提供有关传入 dict 的提示。那好多了。
    • 这可以用多个 WHERE x IN 子句和字典中的多个列表来实现吗?
    • 更正:@Odisseo 是的,使用全能的 OR。例如: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)})
    【解决方案3】:

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

    # using psycopg2
    data=('UK','France')
    
    sql='SELECT * from countries WHERE country IN %s'
    cur.execute(sql,(data,))
    

    在调试期间,您可以检查 SQL 是否正确构建

    cur.mogrify(sql, (data,))
    

    【讨论】:

    • 感谢您的快速回复!
    • 如果您在阅读此答案后仍遇到问题,请非常缓慢地重新阅读。这是一个元组的元组,如果你有它们,你必须删除 %s 周围的参数。这让我大吃一惊,因为我的一个更简单的测试只使用了一个值并且一切正常。完全按照 Bryan 所写的方式进行操作即可。
    • cur.mogrify 是一个很好的提示。我一直忘记那个...?
    猜你喜欢
    • 2016-05-13
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2010-12-07
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多