生成PyODBC查询作为词典的更一般方法?

sta*_*r95 2 python database dictionary pyodbc

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

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()]}
Run Code Online (Sandbox Code Playgroud)

不幸的是,你可以看到,有许多并发症.

例如,查询多个表时; 一些hackish lambdas需要生成结果字典.

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

小智 6

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

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