Is there any way to return dictionary result from adbapi query to MySQL?
[name: 'Bob', phone_number: '9123 4567']
Default returns tuple.
['Bob', '9123 4567']
For simple Python & MySQL we can use MySQLdb.cursors.DictCursor. But how to use it with twisted adbapi
UPD: I solved it but I think there should be better way. My solution: just override *_runInteraction* method of adbapi.ConnectionPool class.
class MyAdbapiConnectionPool(adbapi.ConnectionPool):
def _runInteraction(self, interaction, *args, **kw):
    conn = self.connectionFactory(self)
    trans = self.transactionFactory(self, conn)
    try:
        result = interaction(trans, *args, **kw)
        if(result and isinstance(result[0], (list, tuple))):
            colnames = [c[0] for c in trans._cursor.description]
            result = [dict(zip(colnames, item)) for item in result]         
        trans.close()
        conn.commit()
        return result
    except:
        excType, excValue, excTraceback = sys.exc_info()
        try:
            conn.rollback()
        except:
            log.err(None, 'Rollback failed')
        raise excType, excValue, excTraceback
                You can direct MySQLdb to use DictCursor by passing it as the value for the cursorclass argument to the connect function.  ConnectionPool allows you to pass arbitrary arguments through to the connect method:
import MySQLdb
pool = ConnectionPool("MySQLdb", ..., cursorclass=MySQLdb.cursors.DictCursor)
...
When you run a query, you'll get a dict back instead of a tuple, eg runQuery("SELECT 1") produces a result of ({'1': 1L},)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With