如何安全地参数化动态 python mysql 查询?
How do I securely parameterize a dynamic python mysql query?
我想知道如何在 python 中安全地参数化动态 mysql 查询。通过动态,我的意思是它根据 if 语句的评估方式而变化。
我了解如何使用逗号而不是百分号在 python 中参数化 mysql 查询,如下所示。
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
这是一个 'dynamic query' 的例子。我正在寻找一种比使用百分号更安全的方法。
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
感谢您的见解。
感谢@Nullman,我找到了答案。
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)
我想知道如何在 python 中安全地参数化动态 mysql 查询。通过动态,我的意思是它根据 if 语句的评估方式而变化。
我了解如何使用逗号而不是百分号在 python 中参数化 mysql 查询,如下所示。
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
这是一个 'dynamic query' 的例子。我正在寻找一种比使用百分号更安全的方法。
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
感谢您的见解。
感谢@Nullman,我找到了答案。
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)