On Fri, 25 Mar 2005, Vicki Stanfield wrote:

> I finally gave up and used MySQLdb to connect to my database. It
> connects okay, and returns data, but now I have a new question. I use
> the code below to print the data returned from my query, but I would
> like to make labels at the top of the columns. How do I do this
> dynamically?

Hi Vicki,

Yes, there's a special cursor type that, instead of returning rows of
tuples, returns rows of dictionaries.  Here's an example:

######
>>> import MySQLdb
>>> import MySQLdb.cursors
>>> conn = MySQLdb.connect(db='test_adb',
...                        cursorclass=MySQLdb.cursors.DictCursor)
>>>
>>> cursor = conn.cursor()
>>> cursor.execute("select * from Locus limit 10")
10L
>>> cursor.fetchone()
{'orientation_is_5': 1, 'last_updated': <DateTime object for '2005-03-24
13:48:06.00' at 402faad8>, 'is_deleted': 0, 'name': 'At1g08520',
'representative_model': None, 'is_pseudogene': 0, 'last_updated_by': 1L,
'assigned_to': None, 'update_needed': None, 'gene_model_type': 0L, 'id':
1L, 'chromosome': 1L, 'locked_for_pasa': 0}
######


Hmmm.. that's a little messy.  Let me clean up the output of that a bit
with the pretty printing module 'pprint':

######
>>> import pprint
>>> pprint.pprint(cursor.fetchone())
{'assigned_to': None,
 'chromosome': 1L,
 'gene_model_type': 0L,
 'id': 2L,
 'is_deleted': 0,
 'is_pseudogene': 0,
 'last_updated': <DateTime object for '2005-03-24 13:48:02.00' at
403104b8>,
 'last_updated_by': 1L,
 'locked_for_pasa': 0,
 'name': 'At1g08530',
 'orientation_is_5': 1,
 'representative_model': None,
 'update_needed': None}
######

The output's content itself is probably a bit bizarre to you (It's a gene
from the Arabidopsis plant database)  But I hope the code is clear.
*grin*


If you have more questions, please feel free to ask!

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to