Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMySQL and OrderedDict

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)
like image 976
Paul Carlton Avatar asked Nov 03 '15 16:11

Paul Carlton


People also ask

What is the use of PyMySQL in Python?

PyMySQL is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and contains a pure-Python MySQL client library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb.

What's PyMySQL?

PyMySQL is a pure-Python MySQL client library, based on PEP 249. Most public APIs are compatible with mysqlclient and MySQLdb. PyMySQL works with MySQL 5.5+ and MariaDB 5.5+. MySQL is a leading open source database management system. It is a multiuser, multithreaded database management system.

What is PyMySQL cursors DictCursor?

class pymysql.cursors. DictCursor (connection) A cursor which returns results as a dictionary.


1 Answers

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)
like image 60
vaultah Avatar answered Nov 15 '22 14:11

vaultah