Search code examples
pythonmysqlcode-injection

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.


Solution

  • 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)