Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/psycopg2 WHERE IN语句_Python_Psycopg2_Where In - Fatal编程技术网

Python/psycopg2 WHERE IN语句

Python/psycopg2 WHERE IN语句,python,psycopg2,where-in,Python,Psycopg2,Where In,通过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[…])后出错。除了通过字符串操作之外,还有其他方法可以做到这一点吗 感谢提供了中

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


感谢

提供了中的
运算符,您需要一个而不是,并从SQL字符串中删除括号

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

sql='SELECT * from countries WHERE country IN %s'
cur.execute(sql,(data,))
在调试过程中,您可以检查SQL是否使用

cur.mogrify(sql, (data,))

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

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

您可以直接使用python列表,如下所示。它的行为类似于SQL中的IN运算符,并且在不引发任何错误的情况下处理空白列表

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

感谢您的快速回复!如果你在阅读了这个答案后仍有问题,请慢慢地重新阅读。这是一个元组的元组,如果有%s,则必须删除它们。这让我大吃一惊,因为我的一个更简单的测试只使用了一个值,而且一切都正常。照布莱恩写的那样做就行了。cur.mogrify是一个很好的提示。我总是忘记那件事。。。谢谢你提供的关于传递口述的提示。这要好得多。这可以用多个WHERE x in子句和字典中的多个列表来实现吗?更正:@Odisseo Yes,用万能的或。例如:
cur.execute(“从col-IN%(list1)s或col-IN%(list2)s”所在的表中选择*,{'list1':tuple(1,2,3),'list2'=tuple(4,5,6)}
也可以使用接受的答案,但与
cur.execute(sql,(tuple(data),)