将pyodbc游标结果输出为python字典

2024-05-18 07:54:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将pyodbc游标输出(从.fetchone.fetchmany.fetchall)序列化为Python字典?

我正在使用bottlepy,需要返回dict,以便它可以将其作为JSON返回。


Tags: json字典序列化dict游标pyodbcbottlepyfetchone
3条回答

这是一个简短的版本,你可以使用

>>> cursor.select("<your SQL here>")
>>> single_row = dict(zip(zip(*cursor.description)[0], cursor.fetchone()))
>>> multiple_rows = [dict(zip(zip(*cursor.description)[0], row)) for row in cursor.fetchall()]

当您向列表中添加*时,您可能会注意到,基本上会去掉列表,将各个列表条目作为参数保留给您正在调用的函数。通过使用拉链,我们选择第一个到第n个条目,然后像拉链一样将它们拉在裤子上。

所以通过使用

zip(*[(a,1,2),(b,1,2)])
# interpreted by python as zip((a,1,2),(b,1,2))

你得到

[('a', 'b'), (1, 1), (2, 2)]

由于description是一个包含元组的元组,其中每个元组描述每个列的头和数据类型,因此可以使用

>>> columns = zip(*cursor.description)[0]

相当于

>>> columns = [column[0] for column in cursor.description]

如果您不提前知道列,请使用cursor.description来构建列名列表,并使用zip与每一行一起生成字典列表。示例假设已构建连接和查询:

>>> 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'}]

将@Beargle的结果与bottlepy一起使用,我能够创建这个非常简洁的查询公开端点:

@route('/api/query/<query_str>')
def query(query_str):
    cursor.execute(query_str)
    return {'results':
            [dict(zip([column[0] for column in cursor.description], row))
             for row in cursor.fetchall()]}

相关问题 更多 >