Frage

The Database API docs are here http://www.python.org/dev/peps/pep-0249/#description

If I use MySQLdb to do a Table Join in python, then there may be problems,

def query_db(query, args=(), one=False):
    cur = db.cursor()
    cur.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

result = query_db ('select table1.name, table2.name from table1 inner join table2 on table1.id = table2.id', one=True )
print result       
#{'name':'blah blah'}

The finale result will be a dictionary with only one key name, that is because cur.description has no information about table name, only table colum name, so the table2.name overwrites the table1.name.

Is this a bug?

War es hilfreich?

Lösung

You can try using DictCursor. This is not standard API 2.0.
DictCursor provides a dictionary interface, keys are "column" or "table.column" if there are two columns with the same name.

def query_db(query, args=(), one=False):
    cur = MySQLdb.cursors.DictCursor(db)
    cur.execute(query, args)
    rv = [row for row in cur]
    return (rv[0] if rv else None) if one else rv

Nevertheless I suggets to use a workaround in SQL using AS for specify alias for columns in your select. For example:

select table1.name as `table1.name`, table2.name as `table2.name`
from   table1 inner join table2
on     table1.id = table2.id
...
>>> cur.description
(('table1.name', 253, 32, 32, 32, 0, 0), ('table2.name', 253, 18, 80, 80, 0, 0))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top