查询可选参数
Querying on optional parameters
假设我有一个用户 table 具有年龄和姓名列。我想编写一个函数来查询此 table,选择所有内容,或根据年龄选择。天真地我可能会做
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 传递,则不会被过滤。
假设我有一个用户 table 具有年龄和姓名列。我想编写一个函数来查询此 table,选择所有内容,或根据年龄选择。天真地我可能会做
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 传递,则不会被过滤。