Output pyodbc cursor results as python dictionary

后端 未结 8 1620
孤独总比滥情好
孤独总比滥情好 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 19:11

    I like @bryan and @foo-stack answers. If you are working with postgresql and you are using psycopg2 you could use some goodies from psycopg2 to achieve the same by specifying the cursorfactory being a DictCursor when creating your cursor from the connection, like this:

    cur = conn.cursor( cursor_factory=psycopg2.extras.DictCursor )

    So now you can execute your sql query and you'll get a dictionary to fetch your results, without the need to map them by hand.

    cur.execute( sql_query )
    results = cur.fetchall()
    
    for row in results:
        print row['row_no']
    

    Please note that you'll have to import psycopg2.extras for that to work.

提交回复
热议问题