1. Home
  2. Computing & Technology
  3. Python

Reading from a MySQL Database With Python

From Al Lukaszewski, for About.com

4 of 6

Defining an Instance of Table

Next, we need to define the database and create an instance of Table.

db = MySQLdb.connect( db="testable")
records = Table(db, "test")

Here the database name is 'testable'. The table from 'testable' which we will query is 'test'. It may be stating the obvious, but before executing the program, you must ensure that you actually have access to a database and table by these names (or whatever names you insert into the program). As usual, one can tweak these lines so that the values are derived from the command line by using sys.argv[1] and sys.argv[2], respectively.

We shall instead take the value of sys.argv[1] as the value for the query. So, import the sys module by adding ", sys" to the line where we imported MySQLdb. If you are doing this in the Python shell, simply type:

>>> import sys

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Database Programming
  5. Reading Python Data From a MySQL Database - Defining an Instance of Table

©2009 About.com, a part of The New York Times Company.

All rights reserved.