python - 查询可选参数

标签 python postgresql psycopg2

假设我有一个包含年龄和姓名列的用户表。我想写一个函数来查询这个表,要么选择所有的东西,要么根据年龄选择。天真地我可能会这样做

def query(age=''):
    query_args = ' WHERE {}'.format(age) if age else ''
    db.execute('SELECT * FROM users' + query_args)

显然这是一个可怕的想法,但我不确定处理这种情况的更好方法是什么 - 如果年龄作为参数传递或不传递,编写单独的查询似乎非常难看,尤其是在更多复杂的示例,其中我可能有多个查询参数。

最佳答案

您说得对,构建查询字符串是个糟糕的主意。这个问题不是驱动程序问题。这只是 SQL:

query = """
    select *
    from users
    where
        (%(age)s is null or %(age)s = age)
        and
        (%(name)s is null or %(name)s = name)
"""
parameters = dict(name = None, age = 35)
cursor.execute(query, parameters)

如果某个参数作为 null 传递,则不会被过滤。

关于python - 查询可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37669263/

相关文章:

python - 找到多对点之间最近的 8 连通棋盘距离 : shortest m-path

django - 在 django 中运行syncdb时找不到关系

具有多个 wheres 和 whereNotIn 的 Laravel 5.7 Eloquent 查询

postgresql 服务器不听

python - 将 python 列表插入 Postgres 数据库

python - Flask-SQLAlchemy 引发 : AttributeError: module 'psycopg2' has no attribute 'paramstyle'

python - 使用 Django 提供动态生成的图像

python - 重置根环境 Anaconda

python - 在 Mac OS X 上安装 libpq-dev

python - Loguru 停止在生产中记录 flask 异常