输出pyodbc游标结果作为python字典 [英] Output pyodbc cursor results as python dictionary
本文介绍了输出pyodbc游标结果作为python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何序列化pyodbc游标输出(从 .fetchone
, .fetchmany
或 .fetchall
)作为Python字典?
How do I serialize pyodbc cursor output (from .fetchone
, .fetchmany
or .fetchall
) as a Python dictionary?
我使用bottlepy,需要返回dict,所以它可以返回JSON。 p>
I'm using bottlepy and need to return dict so it can return it as JSON.
推荐答案
如果提前不知道列,请使用 cursor.description 来构建列名称和 zip 与每一行,以产生一个字典列表。示例假定连接和查询已构建:
If you don't know columns ahead of time, use cursor.description to build a list of column names and zip with each row to produce a list of dictionaries. Example assumes connection and query are built:
>>> cursor = connection.cursor().execute(sql)
>>> columns = [column[0] for column in cursor.description]
>>> print columns
['name', 'create_date']
>>> results = []
>>> for row in cursor.fetchall():
... results.append(dict(zip(columns, row)))
...
>>> print results
[{'create_date': datetime.datetime(2003, 4, 8, 9, 13, 36, 390000), 'name': u'master'},
{'create_date': datetime.datetime(2013, 1, 30, 12, 31, 40, 340000), 'name': u'tempdb'},
{'create_date': datetime.datetime(2003, 4, 8, 9, 13, 36, 390000), 'name': u'model'},
{'create_date': datetime.datetime(2010, 4, 2, 17, 35, 8, 970000), 'name': u'msdb'}]
这篇关于输出pyodbc游标结果作为python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文