有没有办法将字典结果从adbapi查询返回给MySQL?
[name: 'Bob', phone_number: '9123 4567']
Run Code Online (Sandbox Code Playgroud)
默认返回元组.
['Bob', '9123 4567']
Run Code Online (Sandbox Code Playgroud)
对于简单的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, *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
Run Code Online (Sandbox Code Playgroud)
您可以DictCursor通过将MySQLdb 作为cursorclass参数的值传递给connect函数来指示MySQLdb使用. ConnectionPool允许您将任意参数传递给connect方法:
import MySQLdb
pool = ConnectionPool("MySQLdb", ..., cursorclass=MySQLdb.cursors.DictCursor)
...
Run Code Online (Sandbox Code Playgroud)
当你运行一个查询时,你会得到一个dict返回而不是一个元组,例如runQuery("SELECT 1")产生一个结果({'1': 1L},)
| 归档时间: |
|
| 查看次数: |
1533 次 |
| 最近记录: |