如何检查值是否在列表中或列表是否为空?

How to check if value is in a list or if the list is empty?

我正在使用 psycopg2 通过 Python 3 访问 PostgreSQL 数据库,我正在尝试查询 select 所有名称为在列表中,如果列表不为空。如果提供的列表为空,我想忽略该条件,即 select 所有用户,无论他们的名字如何。

我已经尝试过以下三个调用:

# 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

加上上面的参数is null,所有的行都会被返回,否则只返回满足条件的行。

Psycopg 将 Python list 改编为 Postgresql array。检查任何 Postgresql array 值是否等于特定值:

where column = any (array[value1, value2])

从一个空的Pythonlist:

得到一个PythonNone,它适用于Postgresqlnull
parameter = [] or None

dictionary 传递给 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