7

I have coded a class to handle mysql connecting using the external modules but when I get data I want it to be returned like:

{ 'id': '1', 'username': 'Test'}

it's currently returned:

(1, u'Test')

The code which I use is:

def executeQuery(self, query):
    if(self.mysqlSuccess):
        cursor = self.cnx.cursor()
        cursor.execute(query)
        for row in cursor:
            print row
executeQuery('SELECT * FROM `users`')
Pie-thorn
  • 271
  • 3
  • 6
  • not exactly a duplicated, but very close (and maybe the answer that op needs) : http://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python – Rod Jul 23 '15 at 14:00
  • possible duplicate of [Python: use mysqldb to import a MySQL table as a dictionary?](http://stackoverflow.com/questions/2180226/python-use-mysqldb-to-import-a-mysql-table-as-a-dictionary) – Joe Doherty Jul 23 '15 at 14:02

2 Answers2

17

I found an answer to my problem when your defining the cursor you do it like this

cursor = db.cursor(dictionary=True)

and the mysql package I was using is mysql.connector

Pie-thorn
  • 271
  • 3
  • 6
5

You can use a DictCursor when initializing your connection to MySQL.

import MySQLdb.cursors

cnx = MySQLdb.connect(user='joe', passwd='password', db='dbname',
                      cursorclass=MySQLdb.cursors.DictCursor)

If you are using a diff mysql package then just check the docs for DictCursor.

Joe Doherty
  • 3,778
  • 2
  • 31
  • 37