Output pyodbc cursor results as python dictionary

后端 未结 8 1561
孤独总比滥情好
孤独总比滥情好 2020-11-29 18:37

How do I serialize pyodbc cursor output (from .fetchone, .fetchmany or .fetchall) as a Python dictionary?

I\'m using bottlepy

相关标签:
8条回答
  • 2020-11-29 19:15

    Mainly going off @Torxed response, I created a full generalised set of functions to find the schema and data into a dictionary:

    def schema_dict(cursor):
        cursor.execute("SELECT sys.objects.name, sys.columns.name FROM sys.objects INNER JOIN sys.columns ON sys.objects.object_id = sys.columns. object_id WHERE sys.objects.type = 'U';")
        schema = {}
    
        for it in cursor.fetchall():
            if it[0] not in schema:
                schema[it[0]]={'scheme':[]}
            else:
                schema[it[0]]['scheme'].append(it[1])
    
        return schema
    
    
    def populate_dict(cursor, schema):
        for i in schema.keys():
            cursor.execute("select * from {table};".format(table=i))
    
            for row in cursor.fetchall():
                colindex = 0
    
                for col in schema[i]['scheme']:
                    if not 'data' in schema[i]:
                        schema[i]['data']=[]
    
                    schema[i]['data'].append(row[colindex])
                    colindex += 1
    
        return schema
    
    def database_to_dict():
        cursor = connect()
        schema = populate_dict(cursor, schema_dict(cursor))
    

    Feel free to go all code-golf on this to reduce the lines; but in the meantime, it works!

    ;)

    0 讨论(0)
  • 2020-11-29 19:19

    For situations where the cursor is not available - for example, when the rows have been returned by some function call or inner method, you can still create a dictionary representation by using row.cursor_description

    def row_to_dict(row):
        return dict(zip([t[0] for t in row.cursor_description], row))
    
    0 讨论(0)
提交回复
热议问题