PyMySQL 和 OrderedDict [英] PyMySQL and OrderedDict
问题描述
我已经使用 PyMySQL 一段时间了,并创建了我自己的包装器,我习惯于速记编写查询.尽管如此,我一直在使用 OrderedDict 创建 CSV 文件,因为我需要保持顺序不变,但我意识到如果我使用 PyMySQL 查询数据库,我将无法获得数据库返回的顺序.如果我只想转储东西而不是手写订单,这对于抽查 CSV 文件来说有点烦人.
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.
我的问题是,如何将 PyMySQL 与 OrderedDict 一起使用?目前我的代码如下:
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
我想要的是,当我滚动光标时,我实际上是按照列从数据库进入的顺序检索它们的 OrderedDict.
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.
类似于:
cursor = conn.cursor(pymysql.cursors.OrderedDict)
推荐答案
您可以使用 cursors.DictCursorMixin
并将其 dict_type
更改为 collections.OrderedDict
(默认为 dict
):
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)
这篇关于PyMySQL 和 OrderedDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!