python – 扭曲的MySQL adbapi返回字典
发布时间:2020-12-16 23:38:44 所属栏目:Python 来源:网络整理
导读:有没有办法将字典结果从adbapi查询返回给 MySQL? [name: 'Bob',phone_number: '9123 4567'] 默认返回元组. ['Bob','9123 4567'] 对于简单的Python MySQL我们可以使用MySQLdb.cursors.DictCursor.但如何使用扭曲的adbapi UPD:我解决了,但我认为应该有更好的
有没有办法将字典结果从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}的结果,) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |