Twisted MySQL adbapi 返回字典

7 投票
1 回答
1660 浏览
提问于 2025-04-17 07:52

有没有办法从adbapi查询中返回字典格式的结果到MySQL?

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

默认情况下返回的是元组。

['Bob', '9123 4567']

对于简单的Python和MySQL,我们可以使用MySQLdb.cursors.DictCursor。但是,如何在twisted的adbapi中使用它呢?


更新:我解决了这个问题,但我觉得应该有更好的方法。我的解决方案是:直接重写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, *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

1 个回答

10

你可以通过在连接数据库时,把DictCursor作为cursorclass参数的值传给connect函数,来让MySQLdb使用字典光标。ConnectionPool允许你把任意参数传递给连接方法:

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

当你执行查询时,你会得到一个dict(字典)作为结果,而不是一个元组。例如,执行runQuery("SELECT 1")会返回({'1': 1L},)这样的结果。

撰写回答