只需将比较运算符作为字符串传递给函数:query1('2013-01', '<=')
这将在查询中插入运算符的字符串,从而导致select *
from table
where number <= 1
and date = 2013-01
请注意,通过插入字符串直接构建SQL查询是SQL注入的潜在向量。如果允许用户提供自己的日期字符串,则用户可能会在其中插入一些SQL代码并运行恶意代码。有关更多信息,请查看查询参数化。你知道吗
如果您想防范SQL注入,应该执行以下操作。允许的操作员列表被仔细地列在白名单上,因此只能使用有效的和安全的操作员。这用于生成查询。然后通过cursor.execute()命令将日期注入到查询中。MySQLdb然后处理从您的数据构造一个安全查询,并且不允许恶意用户插入自己的SQL来代替日期字符串。你知道吗import MySQLdb
def query1(date, comp):
query = '''
select *
from table
where number {comp} 1
and date = %s
'''.format(comp=sql_comp_operator(comp))
cursor.execute(query, (date, ))
return cursor.fetchall()
def sql_comp_operator(comp):
operators = {
'lt': '
'lte': '
'gt': '>',
'gte': '>=',
}
if comp in operators:
return operators[comp]
else:
raise ValueError("Unknown comparison operator '{}'".format(comp))
query1('2013-01', 'lte')