DictCursor available?

Asked by Philipp Oeser

Hi!
First of all: thanx for the work done already!

Here is my question:
Is something like MySQLdb's DictCursor planned? I know I can get around this by inspecting the cursors description, but wanted to ask anyway...

Greetz phi

Question information

Language:
English Edit question
Status:
Answered
For:
MySQL Connector/Python Edit question
Assignee:
Geert JM Vanderkelen Edit question
Last query:
Last reply:
Revision history for this message
Philipp Oeser (philippoeser) said :
#1

Hi, I made something quick, that works for me atm...

Greetz phi
================================================
lDicts = []

if bFetchAll: lResults = oCursor.fetchall()
else: lResults = oCursor.fetchone()

for tResult in lResults:
 dResultDict = {}
 iItemCounter = 0
 for tupleDesc in oCursor.description:
  dResultDict[tupleDesc[0].decode()] = tResult[iItemCounter]
  iItemCounter += 1
 lDicts.append(dResultDict)

return lDicts
================================================

Revision history for this message
Geert JM Vanderkelen (geertjmvdk) said :
#2

(see "Fetching rows as dictionaries with MySQL Connector/Python" http://geert.vanderkelen.org/post/356/ )

With all version of MySQL Connector/Python, you can do the following:

  cnx = mysql.connector.connect(host='localhost',database='test')
  cur = cnx.cursor()
  cur.execute("SELECT c1, c2 FROM t1")
  result = []
  columns = tuple( [d[0].decode('utf8') for d in cur.description] )
  for row in cur:
    result.append(dict(zip(columns, row)))
  cur.close()
  cnx.close()

(FYI: columns is a tuple to make sure it can't change)

With MySQL Connector/Python v0.2, you can specify which cursor class to use when getting a new cursor. Here is how we create a cursor which returns dictionaries:

  import mysql.connector

  class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):

    def fetchone(self):
      row = self._fetch_row()
        if row:
          return dict(zip(self.column_names, self._row_to_python(row)))
        return None

And here is how you use it:

  cnx = mysql.connector.connect(host='localhost',database='test')
  cur = cnx.cursor(cursor_class=MySQLCursorDict)
  cur.execute("SELECT c1, c2 FROM t1")
  rows = cur.fetchall()
  cur.close()
  cnx.close()

Can you help with this problem?

Provide an answer of your own, or ask Philipp Oeser for more information if necessary.

To post a message you must log in.