简体   繁体   中英

How do I securely parameterize a dynamic python mysql query?

I am wondering how to securely parameterize a dynamic mysql query in python. By dynamic, I mean it changes depending on how the if statements evaluate.

I understand how to parameterize a mysql query in python, by using a comma, rather than a percent sign, like as follows.

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

Here is an example of a 'dynamic query'. I am looking to find a more secure way than using the percent sign.

    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

Thank you for your insight.

thanks to @Nullman I came to an answer.

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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