PyMySQL and OrderedDict

泪湿孤枕 提交于 2019-11-30 02:50:56

问题


I've been using PyMySQL for a while now and created my own wrapper that I'm used to to shorthand writing queries. Nonetheless I've been creating CSV files with OrderedDict because I need to keep the order the same but I realize that if I use PyMySQL for querying the database, I will not get the order the database is giving back. This is a little annoying for spot checking CSV files if I wanted to just dump stuff rather than hand write the orders.

My question is, how do I use PyMySQL with OrderedDict? Currently my code is as follows:

import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='', db='test')
cursor = conn.cursor(pymysql.cursors.DictCursor)

So whenever I query, I'll be getting a dictionary back:

cursor.execute("""SELECT * FROM test""")
for row in cursor:
    pp(row)  # gives me dictionary

What I want is that when I roll through cursor I'm actually retrieving an OrderedDict of the columns in the order they come in from the database.

Something like:

cursor = conn.cursor(pymysql.cursors.OrderedDict)

回答1:


You could use cursors.DictCursorMixin and change its dict_type to collections.OrderedDict (the default is dict):

from collections import OrderedDict
from pymysql.cursors import DictCursorMixin, Cursor

class OrderedDictCursor(DictCursorMixin, Cursor):
    dict_type = OrderedDict

Then you can use the new cursor class as shown below

cursor = conn.cursor(OrderedDictCursor)


来源:https://stackoverflow.com/questions/33504938/pymysql-and-ordereddict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!