8

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I've been using namedtuple for weeks to acomplish a simliar result, thanks
It should be something like connection.cursor instead of db.cursor, or?
8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.