简体   繁体   English

查询可选参数

[英]Querying on optional parameters

Suppose I have a user table with age and name columns. 假设我有一个带有年龄和名称列的用户表。 I would like to write a function to query this table, either selecting everything, or selecting based on age. 我想编写一个函数来查询这个表,要么选择所有内容,要么根据年龄进行选择。 Naively I might do 天真,我可能会这样做

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

obviously this is a horrible idea, but I'm not sure what the better way to deal with this situation is - it seems pretty ugly to write a separate query if age is passed as an argument or it's not, especially in more complicated examples where I might have multiple parameters to the query. 显然这是一个可怕的想法,但我不确定处理这种情况的更好方法是 - 如果将年龄作为参数传递或者不是,那么编写单独的查询似乎非常难看,尤其是在更复杂的示例中我可能有多个查询参数。

You are right in that building a query string is a terrible idea. 你是对的,建立一个查询字符串是一个可怕的想法。 This problem is not a driver one. 这个问题不是驱动程序。 It is just SQL: 它只是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)

If a certain parameter is passed as null it will not be filtered. 如果某个参数作为null传递,则不会对其进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM