Search code examples
pythonmysqlformattingtornado

Passing in parameters to torndb.query()


I have the database connection set up in python using torndb.

I'm having issues trying to query it using torndb.query(query, *parameters, **kwargs)

query = """
SELECT *
FROM students
WHERE name LIKE "%s"
AND score LIKE "%s"
"""

parameters = ["Jack", "A"]
students = db.query(query, parameters)

Although this query doesn't return anything even though there are matches in the mySQL database when running the raw query directly ->

SELECT *
FROM students
WHERE name LIKE "Jack"
AND score LIKE "A

I would like to figure out how to make this query work using the parameters arg in the torndb.query() function, I know you can do this by formatting the actual query string but this is not my objective.


Solution

  • query() takes one argument for each %s in the query string:

    db.query(query, "Jack", "A")
    

    You're passing them as a single list object. To have Python expand the list into separate parameters, put an asterisk before it:

    db.query(query, *parameters)