Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Returning the output as a dictionary - MySQL

Tags:

python

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`')
like image 947
Pie-thorn Avatar asked Dec 02 '22 16:12

Pie-thorn


2 Answers

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

like image 67
Pie-thorn Avatar answered Dec 05 '22 05:12

Pie-thorn


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.

like image 33
Joe Doherty Avatar answered Dec 05 '22 05:12

Joe Doherty