Using user-defined variables
What if you want to specify a different price floor every time you run the search? What if you didn't want to use a floor but specify the price exactly? What if you wanted to reuse part of the statement and automate queries by fish name instead of retrieving all of them at once? Under such circumstances, you need to be able to handle variables in your SELECT
statements.
MySQL for Python passes variables to MySQL in the same way that Python formats other kinds of output. If we wanted to specify just the floor of the search, we would assign the variable as any other and pass it to the execute()
method as a string. Consider the following snippet from a Python terminal session:
>>> value = "7.50" >>> command = cur.execute("""SELECT * FROM menu WHERE price = %s""" %(value)) >>> results = cur.fetchall() >>> for record in results: ... print record[0], ". ", record[1], "(%s)" %record[2] ... 1 . tuna (7.50)
If we wanted the user...