mxODBC question

Gillou glenfant at
Mon Feb 12 12:00:40 CET 2001

I use this small module with mxODBC. These functions (selectdict and
fetchdict) return a dictionnary of tuples.
The keys of the dictionnary are the names of the fields in the 'select'
statement. the tuples are the values of the columns.

Warning: like these function make a "curs.fetchall()", do not use select
statement like "select * from agianttable" or you'll run out of memory.

You can use these like below:

curs = aconnection.cursor()
curs.execute('select name city from people')
result = fetchdict(curs)
count = len(result['name'])
for i in (0, count):
    print result['name'][i], result['city'][i]

or like this if there is no reusable cursor:

result= selectdict(aconnection, 'select name city from people')
count = len(result['name'])
for i in (0, count):
    print result['name'][i], result['city'][i]

Maps the result of a "select ..." query to a dictionnary.
Each key of the dictionnary is a field name (depending on query)
Each value is a tuple of consecutive data of the field (order depending on
Requires mxOdbc package.
Ifield = 0

def _getcol(seq):
    global Ifield
    return seq[Ifield]

def fetchdict(curs):
    '''curs is the cursor which just executed a "select..." statement.'''
    global Ifield
    fldnlist = map(lambda x: x[0], curs.description)
    fetchresult = curs.fetchall()
    Ifield = 0
    for fldname in fldnlist:
        fdict[fldname] = tuple(map(_getcol, fetchresult))
        Ifield = Ifield + 1
    return fdict

def selectdict(cnx, req):
    '''cnx is a connection object created with mxOdbc
    req is an SQL "select..." query'''
    curs = cnx.cursor()
    rtdict = fetchdict(curs)
    return rtdict
"Scott Hathaway" <slhath at> a écrit dans le message news:
nTDh6.66287$bb.1038987 at
> I am using mxODBC to access db's with no problem, but I have a question.
> I use a sql call as follows:
> select username from users;
> Then, I make a call as follows:
> data = c.fetchall()
> Then, to access the first value of the first (and only) field, I have to
> use:
> theValue = data[0][0]
> This is ugly.  Is there a way to do something like:
> theValue = data[0]['firstname']
> Or anything more easy to discern for code readability?
> Thanks,
> Scott

More information about the Python-list mailing list