mxODBC question

Gillou glenfant at equod.com.nospam
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:

<sample1>
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]
</sample1>

or like this if there is no reusable cursor:

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

<script>
'''fetchdict.py
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
query)
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
    fdict={}
    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()
    curs.execute(req)
    rtdict = fetchdict(curs)
    curs.close()
    return rtdict
</script>
"Scott Hathaway" <slhath at home.com> a écrit dans le message news:
nTDh6.66287$bb.1038987 at news1.rdc1.tx.home.com...
> I am using mxODBC to access db's with no problem, but I have a question.
If
> 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