我正在使用 psycopg2
通过 Python 3 访问 PostgreSQL 数据库,我正在尝试进行查询,我想在其中选择名称在列表中的所有用户,如果列表不为空。如果提供的列表为空,我想忽略该条件,即选择所有用户而不考虑他们的名字。
我已经尝试过以下三个调用:
# Using list
cursor.execute(
"SELECT age FROM user WHERE %(names) = '{}' OR user.name IN %(names)s",
{'names': []},
)
# Using tuple
cursor.execute(
"SELECT age FROM user WHERE %(names) = () OR user.name IN %(names)s",
{'names': ()},
)
# Using both list and tuple
cursor.execute(
"SELECT age FROM user WHERE %(names_l) = '{}' OR user.name IN %(names_t)s",
{'names_l': [], 'names_t': ()},
)
但它们都从某一点或另一点引发无效语法错误:
# Using list
psycopg2.ProgrammingError: syntax error at or near "'{}'"
LINE 17: user.name IN '{}'
# Using tuple
psycopg2.ProgrammingError: syntax error at or near ")"
LINE 16: () == ()
# Using both list and tuple
psycopg2.ProgrammingError: syntax error at or near ")"
LINE 17: user.name IN ()
最佳答案
对于可选参数,您需要一个 SQL where
子句,例如:
where column = :parameter or :parameter is null
当参数 为 null
时,将返回所有行,否则仅返回满足条件的行。
Psycopg 将 Python list
适配为 Postgresql array
。检查是否有任何 Postgresql array
值等于某个值:
where column = any (array[value1, value2])
要从一个空的 Python list
中获取一个适用于 Postgresql null
的 Python None
:
parameter = [] or None
将字典
传递给cursor.execute
方法避免参数参数中的参数重复:
names = ['John','Mary']
query = """
select age
from user
where user.name = any (%(names)s) or %(names)s is null
"""
print (cursor.mogrify(query, {'names': names or None}).decode('utf8'))
#cursor.execute(query, {'names': names or None})
输出:
select age
from user
where user.name = any (ARRAY['John', 'Mary']) or ARRAY['John', 'Mary'] is null
当列表为空时:
select age
from user
where user.name = any (NULL) or NULL is null
http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
关于postgresql - 如何检查值是否在列表中或列表是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869058/