Pie-thorn
Pie-thorn

Reputation: 289

Python - Returning the output as a dictionary - MySQL

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`')

Upvotes: 8

Views: 7505

Answers (2)

Pie-thorn
Pie-thorn

Reputation: 289

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

Upvotes: 17

Joe Doherty
Joe Doherty

Reputation: 3948

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.

Upvotes: 8

Related Questions