0

I would like to be able to use my SQL table in python. I managed to connect and access my table using the code.

I would like to know if it was possible to retrieve the column names in my code.

I already have my colomns:

ACTION    |    MANAGER
123             XYZ
456             ABC
PersonnesQuery = "SELECT........"
cursor = mydb.cursor()
cursor.execute(PersonnesQuery)
records_Personnes = cursor.fetchall()


for row in records_Personnes:
   if (row["MANAGER"] == "XYZ"):
                ..................
   elif (row["MANAGER"] == "ABC"):
                ................    


the way quoted does not seem to work. However, it works with the number, for example row[0]. But I would like by column name

Oliv
  • 120
  • 1
  • 12

2 Answers2

0

In order to access a field by key, in this case "MANAGER", row should be a dict. But due to the fact that you can access row by index, row is type list. Meaning you can't access by key when using .fetchall() because it returns a list.

gdrubich
  • 5
  • 2
0

I'm assuming you're using the pymysql library, in which case there is a specific kind of cursor called a DictCursor. This will return the results as a dictionary rather than a list.

cursor = mydb.cursor(pymysql.cursors.DictCursor)
cursor.execute(PersonnesQuery)
records_Personnes = cursor.fetchall()
Duck Hunt Duo
  • 299
  • 1
  • 11