Search code examples
pythonmysqlmysql-connector-python

MySQL connector with Python: getting data by field name


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


Solution

  • 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.