MySQLdb DictCursor scrambles field order
Chris Gonnerman
chris.gonnerman at newcenturycomputers.net
Wed Jul 31 01:27:16 EDT 2002
----- Original Message -----
From: "HW" <google at thegoldensun.com>
> Hello,
>
> I am viewing some MySQL tables via Python CGI; I use the
> MySQLdb.DictCursor in order to return the field names as well as the
> data, so I can output a table with the field names as column headings.
>
> Unfortunately, the DictCursor seems to scramble the order of fields,
> eg:
> "SELECT field1, field2, field3 FROM table"
> which returns the fields in order when using a standard cursor, seems
> to rearrange the order (randomly?) with a DictCursor.
What else did you expect? The fields are returned in the form of a
mapping, which has no required or inate order to it. It's a hash.
Again, why do you care? Are you iterating over the fields using the
record's .keys() method? Keep track of the keys in a list if you need
a specific order:
keys = [ "field1", "field2", "field3" ]
recs = cursor.fetchall()
for record in recs:
for key in keys:
print "%s: %s" % (key, record[key])
(sloppy example I know... hacked it out in a hurry.)
> I am using MySQLdb 0.9.1, Python 2.1, 3.23.51-nt under Win XP; I have
> had the same trouble in a similarly numbered Linux version.
>
> Thanks for any help!
>
> HW
Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net
http://newcenturycomputers.net
More information about the Python-list
mailing list