Welcome, guest | Sign In | My Account | Store | Cart

This class allows you to access the rows of a cursor by field name.

Python, 4 lines
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

3 comments

Serdar Tumgoren 14 years ago  # | flag

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:

  • Recipe 81252: Using dtuple for flexible query result access
  • Recipe 52293: Generate Field Name-to-Column Number Dictionary

Also worth noting is sqlite3's approach to this problem:

Steve Orr 14 years ago  # | flag

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

Steve Orr 14 years ago  # | flag

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
Created by Ricardo Araoz on Fri, 9 Apr 2010 (MIT)
Python recipes (4591)
Ricardo Araoz's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks