This class allows you to access the rows of a cursor by field name.
1 2 3 4 | class reg(object):
def __init__(self, cursor, row):
for (attr, val) in zip((d[0] for d in cursor.description), row) :
setattr(self, attr, val)
|
May be used by any database module. Simplifies access to the different fields, instead of using non intuitive numbers you use the names of your fields. Usage :
>>> for row in cursor.fetchall() :
... r = reg(cursor, row)
... print r.SomeField, r.SomeOtherField, r.AnotherFieldName, r.FinalField
Nicely done. This is the most elegant solution to this task that I've run across. Below are some other approaches for flexible handling of database query results:
Also worth noting is sqlite3's approach to this problem:
You might want to look at the "high performance" namedtuple collections available in 2.6:
rdef = namedtuple('dataset', ' '.join([x[0] for x in cursor.description])) for r in map(rdef._make, cursor.fetchall()): print r.field1, r.field2, r.etc
You might want to look at the "high performance" namedtuple collections available in 2.6: