Remap Mysql tuple to dictionary

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Tue Sep 26 01:41:18 EDT 2006


In message <2rTRg.95640$AD5.1277027 at phobos.telenet-ops.be>, Pom wrote:

> I want to convert a Mysql resulset to a dictionary.

Here's a function that does this one row at a time:

def GetEachRecord(TableName, Fields, Condition, Values, Extra = "") :
    """generator which does an SQL query which can return 0 or more
    result rows, yielding each record in turn as a mapping from
    field name to field value. TableName can be a single table name,
    or a comma-separated list of names for a join. Extra allows
    specification of order/group clauses."""
    Cursor = sql.conn.cursor() # modify this as appropriate
    Cursor.execute \
      (
            ", ".join(Fields)
        +
            " from "
        +
            TableName
        +
            " where "
        +
            Condition
        +
            " "
        +
            Extra,
        Values
      )
    while True :
        NextRow = Cursor.fetchone()
        if NextRow == None :
            Cursor.close()
            raise StopIteration
        #end if
        yield dict(zip(Fields, NextRow))
    #end while
#end GetEachRecord

You'd use this something like

    for Link in GetEachRecord(...) :
        ... Link[fieldname] ... blah-blah ...




More information about the Python-list mailing list