bobsedge's Python - MySQL Tutorial

One of the primary reasons we advocated python in the previous tutorial is it's easy handling of data with complex relationships beyond flat text. But this is useless if we can't get the information out of our database! This document describes the interface between python and MySQL using a common library called MySQLdb.

API Standards

Just as SQL is the standard language for querying many database servers, there are standards for designing programatic interfaces to databases to minimize the effort porting code if you change database server. MySQLdb implements python's DB-API v2.0 standard, which in turn is based on other standards for the C programming language. You can reference DB-API here, or investigate MySQLdb by doing the following in the interpreter:

>>> import MySQLdb
>>> help("MySQLdb")
(all other examples in this text require you to import MySQLdb or DurandLab first).

Connections and Cursors

Connecting to the DB is a 2-step process.

Retrieving Data

Now let's work with an entire block of code. The purpose of this code is to retrieve all accessions from SwissProt that refer to mouse proteins. Afterwards, we'll create a dictionary connecting these accessions to entry names.

     1	import DurandLab
     2	import sys
     3	
     4	#establish connection
     5	db = DurandLab.pushConn(dbName='SwissProt')
     6	c = db.cursor()
     7	
     8	#retrieve accessions
     9	n = c.execute("SELECT accession FROM entries WHERE INSTR('gb_taxID_list', '10090')")
    10	if n == 0 :
    11		print "No mouse proteins found!"
    12		sys.exit(1)
    13	accessions = c.fetchall()
    14	
    15	#unpack accessions
    16	accessions = map(lambda x : x[0], accessions)
    17	
    18	#create dictionary
    19	dict = {}
    20	for accession in accessions:
    21		c.execute("SELECT name WHERE accession = %r"%accession)
    22		name = c.fetchone()[0]
    23		dict[accession] = name
    

State Info

Examine dir(MySQLdb.cursor) for more functions about the state of the database. Here are some useful ones:

back home
bobsedge@andrew.cmu.edu