2

I have to retrieve data from a database. Right now i am using the following code:

import mysql.connector

connection = mysql.connector.connect(user, password, host, database)

cursor = connection.cursor()
cursor.execute(*Query*)
data = cursor.fetchall()
name = data[0][0]
surname = data[0][1]

I would need to access the data by field name instead of raw indexes. For instance something like that

name = data[0]['name']
surname = data[0]['surname']

Thanks

4
  • 1
    try cursor = cnx.cursor(dictionary=True) in python 3 Commented Jul 24, 2018 at 8:28
  • i am running python 2.7 Commented Jul 24, 2018 at 8:29
  • @Gidx88 what is the version of your connector package? According to the docs dictionary is available since Connector/Python 2.0.0. Apparently not restricted to Python 3 Commented Jul 24, 2018 at 8:34
  • I think dictionary is actually working but for some reasons i won't find my key. This is the code print("Countries in Europe:") for row in cursor: print("* {mykey}".format(Name=row['mykey'])), i have a column named "mykey" but i get a Keyerror: 'mykey' Commented Jul 24, 2018 at 9:56

2 Answers 2

5

One option is to use MySQLdb. Then you can change:

cursor = connection.cursor()

To:

cursor = connection.cursor(MySQLdb.cursors.DictCursor) 

and access the values by field names instead indexes.

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

2 Comments

Can't get to import the MySqlDB module
@Gidx88 follow the instructions here: github.com/farcepest/MySQLdb1/blob/master/INSTALL
2

According to mysql-connector-python documentation, there are two ways to achieve this.

Manually:

cursor = cnx.cursor()
cursor.execute(...)
row = dict(zip(cursor.column_names, cursor.fetchone()))

With MySQLCursorDict class:

cursor = cnx.cursor(dictionary=True)

Comments

Your Answer

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