Python: Associative Results with the MySQLdb library

July 8, 2011 | Reading time: 1 minutes

This is more of a personal reminder as it’s not the default behavior as it is in most modern database libraries…

I’ve highlighted the important bits for associative results in white below

#!/usr/bin/python
# Note the MySQLdb.cursors import statement
#    and the cursorclass declaration in the connect string.
import MySQLdb
import MySQLdb.cursors

oDBConn=MySQLdb.connect(user="user",
			passwd="pass",
			db="db",
			host="localhost",
			compress=1,
			cursorclass=MySQLdb.cursors.DictCursor)
oCursor=oDBConn.cursor()
oCursor.execute("select `field1`,`field2`,`field3` from `mytable`")

while(1):
	LogString = ""
	oRow = oCursor.fetchone ()
	if oRow == None:
		break
	sField1 = oRow["field1"]
	sField2 = oRow["field2"]
	sField3 = oRow["field3"]

The

 tag formatting above may be a bit difficult depending on your browser… but you should be able to copy and paste the entire codeblock with no difficulty.