I just started using MySQLdb the other day. I was hoping that the
default cursor had a method that returned the field names from a
query. It seems there is not, so I tried using the dict cursor like:
con = MySQLdb(foo)
cur = MySQLdb.cursors.DictCursor( con )
I then discovered (from the warnings emiited and looking a the source)
that the dict methods are deprectated (to be removed in version 1.3).
So, I'm not actually interested in getting the query results as a
dictionary, I just want to get the field names. From looking at
the source there didn't appear to be any way of doing this.
Have I missed somthing? Or perhaps new methods will be introduced in v 1.3?
Or maybe there are no plans for this type functionality?
Any comments would be truly appreciated.
TIA,
Evo.
PS.
Of course I know I could try to parse the query string myself to extract the
information I require, but I am really hoping there is a cleaner way.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
thanks for your speedy and helpful reply. Seems I should have
looked at the code more carefully: the description variable in
the cursor class is indeed what I was looking for.
Thanks again,
Evo.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Hi all,
I just started using MySQLdb the other day. I was hoping that the
default cursor had a method that returned the field names from a
query. It seems there is not, so I tried using the dict cursor like:
con = MySQLdb(foo)
cur = MySQLdb.cursors.DictCursor( con )
I then discovered (from the warnings emiited and looking a the source)
that the dict methods are deprectated (to be removed in version 1.3).
So, I'm not actually interested in getting the query results as a
dictionary, I just want to get the field names. From looking at
the source there didn't appear to be any way of doing this.
Have I missed somthing? Or perhaps new methods will be introduced in v 1.3?
Or maybe there are no plans for this type functionality?
Any comments would be truly appreciated.
TIA,
Evo.
PS.
Of course I know I could try to parse the query string myself to extract the
information I require, but I am really hoping there is a cleaner way.
Hi Andy,
thanks for your speedy and helpful reply. Seems I should have
looked at the code more carefully: the description variable in
the cursor class is indeed what I was looking for.
Thanks again,
Evo.
This is also documented in the DB-API spec, a.k.a. PEP-249
You should do this to create a cursor:
cursor = con.cursor(MySQLdb.cursors.DictCursor)
Getting the field names is easy. If there were no DictCursors, you could do this:
c = db.cursor() # standard cursor
c.execute(query)
columns = [ col[0] for col in c.description ]
while row in c:
dict_row = dict(zip(columns, row))
1.3 will probably have some alternate mechanism to get dictionaries back directly.