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
asked Jul 24, 2018 at 8:23
user9704406
2 Answers 2
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.
answered Jul 24, 2018 at 9:38
deChristo
1,8882 gold badges21 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
deChristo
@Gidx88 follow the instructions here: github.com/farcepest/MySQLdb1/blob/master/INSTALL
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
default
cursor = cnx.cursor(dictionary=True)in python 3dictionaryis available since Connector/Python 2.0.0. Apparently not restricted to Python 3for row in cursor: print("* {mykey}".format(Name=row['mykey'])), i have a column named "mykey" but i get a Keyerror: 'mykey'