#9 New cursor type that integrates ...

MySQLdb-1.0
closed
Andy Dustman
MySQLdb (285)
5
2012-09-19
2001-07-17
Dirk Holtwick
No

SUGGESTION:

The code below shows an implementation of a new
cursor/ result model. It integrates tuple- and
dictionary functionality. Could be a usefull feature,
but needs still some optimization. It would be usefull
to have the tablenames also so that someone could get
an entry by doing like r["table.field"].


import MySQLdb
import MySQLdb.cursors

class MyRow:

def __init__(self, ptr, seq):
    """
    ptr like

{"id":0, "name":1, "tab.name":1, "jojo":2, ...}
seq like (66L, "Valentina", 1, ...)
"""
self.seq = seq
self.ptr = ptr

def __getitem__(self, name):
    try:
        if type(name)==type(""):
            return self.seq[self.ptr[name]]
        else:
            return self.seq[name]
    except:
        raise "value doesn't exist"

def __len__(self):
    return len(self.seq)

def get(self, name, default=None):
    try:
        return self.__getitem__(name)
    except:
        return default

def has_key(self, name):
    return self.ptr.has_key(name)

def items(self):
    raise "not implemented, because it would be

confusing. use values() and keys() instead"

def values(self):
    return self.seq

def keys(self):    
    return self.ptr.keys()

class MyCursorMixIn:

_fetch_type = 0

def _createptr(self):
    ptr = {}
    i   = 0
    for k in self.description:
        ptr[k[0]] = i
        i = i + 1
    return ptr

def fetchoneObj(self):
    r = self.fetchone()
    return MyRow(self._createptr(), r)

def fetchmanyObj(self, size=None):
    r = list(self.fetchmany(size))
    p = self._createptr()
    for i in range(len(r)):
        r[i] = MyRow(p, r[i])
    return r

def fetchallObj(self):
    r = list(self.fetchall())
    p = self._createptr()
    for i in range(len(r)):
        r[i] = MyRow(p, r[i])
    return r

class MyCursor(MySQLdb.cursors.Cursor, MyCursorMixIn):
pass

conn = MySQLdb.connect(db="manager")
cur = conn.cursor(MyCursor)
cur.execute("select * from mitarbeiter")

print cur.description
for o in cur.fetchallObj():
print o[0],
print o["name"]

Discussion

  • Andy Dustman
    Andy Dustman
    2001-07-17

    Logged In: YES
    user_id=71372

    This isn't a bug.

    The Cursor class family is designed to be extensible. This
    kind of extension belongs in another module. Also see
    http://dustman.net/andy/python/SQLDict for a cross-platform
    (multiple database module) way of doing this.