MySQLdb where's fetchoneDict()?

Hamish Lawson hamish_lawson at yahoo.co.uk
Mon Oct 1 05:17:50 EDT 2001


Gerhard Häring wrote:

> > I'd probably subclass the cursor class to have the desired behaviour, i.
> > e. a fetchoneDict() method that only uses stuff from the DB-API. That's
> > not too difficult, it would only involve cursor.fetchone() and
> > cursor.description. Then you'd need to subclass the Connection class to
> > return an instance of your subclassed Cursor class instead.
> 
> Ugh. In reality, this gets uglier than I thought. Which probably means
> that the idea wasn't really that good.

I'm not sure it needs to get too much more ugly. Recently I wanted to
provide dictfetch* provides for ingmod, a module for interfacing to
Ingres databases. For the sake of generality this is done with a
DictCursor class that wraps *any* existing DB-API cursor object,
adding the extra methods while delegating the others to the original
cursor (as seen in DictCursor.py below). I then wrote an ingresdb
module (also seen below) that wraps ingmod, but which uses DictCursor
for its cursors. (ingresdb also provides a fetchall method, since this
is not implemented in ingmod.)

Hamish Lawson


===DictCursor.py===============================================================

def make_dict(keys, values):
    dict = {}
    for key, value in map(None, keys, values):
        dict[key] = value
    return dict
        
class DictCursor:

    def __init__(self, cursor):
        self.cursor = cursor

    def execute(self, query, params=None):
        if params:
            self.cursor.execute(query, params)
        else:
            self.cursor.execute(query)
        self.columns = [col_desc[0] for col_desc in
self.cursor.description]
        
    def dictfetchone(self):
        row = self.cursor.fetchone()
        return make_dict(self.columns, row)
        
    def dictfetchall(self):
        return [make_dict(self.columns, row) for row in
self.cursor.fetchall()]

    def __getattr__(self, attr):
        return getattr(self.cursor, attr)

===ingresdb.py===============================================================

from ingmod import *
import ingmod
from DictCursor import DictCursor

class Cursor:

    def __init__(self, cursor):
        self.cursor = cursor

    def fetchall(self):
        results = []
        while 1:
            row = self.cursor.fetchone()
            if not row:
                break
            results.append(row)
        return results

    def __getattr__(self, attr):
        return getattr(self.cursor, attr)

class Connection:

    def __init__(self, dsn, user=None):
        self.conn = ingmod.connect(dsn, None, user)

    def cursor(self):
        return DictCursor(Cursor(self.conn.cursor()))

    def __getattr__(self, attr):
        return getattr(self.conn, attr)
    
def connect(dsn, user=None):
    return Connection(dsn, user)



More information about the Python-list mailing list