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

Mar*_*nen 6 postgresql parameters psycopg2 list where-in

我正在使用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': ()},
)
Run Code Online (Sandbox Code Playgroud)

但是它们都从某一点或另一点引发了无效的语法错误:

# 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 ()
Run Code Online (Sandbox Code Playgroud)

Clo*_*eto 5

对于可选参数,您需要一个 SQLwhere子句,例如:

where column = :parameter or :parameter is null
Run Code Online (Sandbox Code Playgroud)

使用上述参数时,is null将返回所有行,否则仅返回满足条件的行。

Psycopg 使 Python 适应listPostgresql array。要检查是否有任何 Postgresqlarray值等于某个值:

where column = any (array[value1, value2])
Run Code Online (Sandbox Code Playgroud)

要从一个空的 Python获得一个None适用于 Postgresqlnull的 Python list

parameter = [] or None
Run Code Online (Sandbox Code Playgroud)

将 a 传递dictionarycursor.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})
Run Code Online (Sandbox Code Playgroud)

输出:

select age
from user
where user.name = any (ARRAY['John', 'Mary']) or ARRAY['John', 'Mary'] is null
Run Code Online (Sandbox Code Playgroud)

当列表为空时:

select age
from user
where user.name = any (NULL) or NULL is null
Run Code Online (Sandbox Code Playgroud)

http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries