Neat access to db query results

Paj paj at pajhome.org.uk
Sat Jul 23 10:40:21 CEST 2005


Hi,

I often wish for a really high-level way to access db results, being
willing to forego some efficiency. I came up with a class you can use
like:

  cur = db.cursor()
  cur.execute('select abc, def from blah')
  for row in dbcur_iter(cur):
    print row['abc'], row['def']

Here's the class:

  class dbcur_iter:
    def __init__(self, cur):
      self.cur = cur
      self.names = [x[0] for x in cur.description]
    def __iter__(self):
      return self
    def next(self):
      x = cur.fetchone()
      if x is None:
        raise StopIteration
      return dict(zip(self.names, x))

Hope you find it useful! Do send me any feedback.

Paul




More information about the Python-list mailing list