gpt4 book ai didi

python - 将 PyODBC 查询生成为 dict 的更通用方法?

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:51 24 4
gpt4 key购买 nike

以下是我根据数据库查询结果创建字典的一般类方法:

def make_schema_dict(self):
schema = [i[2] for i in self.cursor.tables()
if i[2].startswith('tbl_') or i[2].startswith('vw_')]

self.schema = {table: {'scheme': [row.column_name for row
in self.cursor.columns(table)]}
for table in schema}

def last_table_query_as_dict(self, table):
return {'data': [{col: row.__getattribute__(col) for col in self.schema[table]['scheme']
if col != 'RowNum'} for row in self.cursor.fetchall()]}

不幸的是,如您所见,有很多并发症。

比如查询多张表时;生成结果字典需要一些 hackish lambda。

你能想到一些更通用的方法吗?

最佳答案

您应该能够使用 row.cursor_description使这更简单。这应该为您提供结果的字典列表:

    [{c[0]: v for (c, v) in zip(row.cursor_description, row)} for row in self.cursor.fetchall()]

关于python - 将 PyODBC 查询生成为 dict 的更通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com