【发布时间】:2017-06-11 15:56:44
【问题描述】:
我正在使用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 ()
【问题讨论】:
标签: postgresql list parameters psycopg2 where-in