Passing a query to MySQL
We have just seen how to form a query for a generic MySQL session. While that was not particularly difficult, using MySQL for Python is even easier. For this next section, we will be working against a database fish
with a table menu
that has the following contents:
+----+----------------+-------+ | id | name | price | +----+----------------+-------+ | 1 | tuna | 7.50 | | 2 | bass | 6.75 | | 3 | salmon | 9.50 | | 4 | catfish | 5.00 | | 5 | trout | 6.00 | | 6 | haddock | 6.50 | | 7 | yellowfin tuna | 12.00 | +----+----------------+-------+
As discussed in Chapter 1, Python's interface with MySQL requires a cursor. It is through the cursor
object that we pass commands to MySQL. So, we import MySQL for Python, log into our database fish
and create the cursor as follows:
import MySQLdb mydb = MySQLdb.connect(host = 'localhost', user = 'skipper', ...