python – 扭曲的MySQL adbapi返回字典

有没有办法将字典结果从adbapi查询返回给
MySQL?

[name: 'Bob',phone_number: '9123 4567']

默认返回元组.

['Bob','9123 4567']

对于简单的Python& MySQL我们可以使用MySQLdb.cursors.DictCursor.但如何使用扭曲的adbapi

UPD:我解决了,但我认为应该有更好的方法.我的解决方案:只需覆盖adbapi.ConnectionPool类的* _runInteraction *方法.

class MyAdbapiConnectionPool(adbapi.ConnectionPool):
def _runInteraction(self,interaction,*args,**kw):
    conn = self.connectionFactory(self)
    trans = self.transactionFactory(self,conn)
    try:
        result = interaction(trans,**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,excTraceback

解决方法

您可以通过将其作为cursorclass参数的值传递给connect函数来指示MySQLdb使用DictCursor. ConnectionPool允许您将任意参数传递给connect方法:

import MySQLdb
pool = ConnectionPool("MySQLdb",...,cursorclass=MySQLdb.cursors.DictCursor)
...

当你运行一个查询时,你会得到一个dict而不是一个元组,例如runQuery(“SELECT 1”)产生一个({‘1’:1L}的结果,)

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。