[Tutor] Fetching dictionaries using MySQLdb

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 8 20:19:02 CEST 2005



On Mon, 8 Aug 2005, Jan Eden wrote:

> Is there a recommended way to receive the results of an SQL query in the
> form I need? Or do I have to create a dictionary of fieldname tuples
> which can be zipped with the query result tuple?


Hi Jan,

MySQLdb supports the concept of customized cursor types.  They have a
particular cursor class that returns dictionary objects:

######
>>> import MySQLdb
>>> import MySQLdb.cursors
>>> MySQLdb.cursors.DictCursor
<class 'MySQLdb.cursors.DictCursor'>
######


When we construct a connection object, we can tell MySQL to construct
those kind of custom cursors by default:

######
>>> conn = MySQLdb.connect(db='test_adb',
...                        cursorclass=MySQLdb.cursors.DictCursor)
>>> cursor = conn.cursor()
>>> cursor.execute("""select name, start_coordinate,
...                                end_coordinate
...                   from BAC""")
1624L
>>>
>>> cursor.fetchone()
{'name': 'F10A5', 'end_coordinate': 28462975L, 'start_coordinate':
28333429L}
>>> cursor.fetchone()
{'name': 'T12M4', 'end_coordinate': 3002250L, 'start_coordinate':
2942990L}
>>> cursor.fetchone()
{'name': 'T12I7', 'end_coordinate': 24869607L, 'start_coordinate':
24834300L}
######


Good luck!



More information about the Tutor mailing list