我想知道如何在python中安全地参数化动态mysql查询。通过动态,我的意思是它会根据if语句的评估方式而改变。
我理解如何在python中使用逗号而不是百分号来参数化mysql查询,如下所示。
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
以下是动态查询的示例'。我希望找到比使用百分号更安全的方法。
def queryPhotos(self, added_from, added, added_to):
sql = "select * from photos where 1=1 "
if added_from is not None:
sql = sql + "and added >= '%s' " % added_from
if added is not None:
sql = sql + "and added = '%s' " % added
if added_to is not None:
sql = sql + "and added <= '%s' " % added_to
感谢您的见解。
答案 0 :(得分:0)
def queryPhotos(self, added_from, added, added_to):
vars = []
sql = "select * from photos where 1=1 "
if added_from is not None:
sql = sql + "and added >= %s "
vars.append(added_from)
if added is not None:
sql = sql + "and added = %s "
vars.append(added)
if added_to is not None:
sql = sql + "and added <= %s "
vars.append(added_to)
vars = tuple(vars)
results = c.execute(sql, vars)