I am storing my column data into Python list, Name of the list should be the same as the column name.

I am using this code:

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "root",
    passwd = "",
    database = "DB"
)
cursor = db.cursor()
query = "SELECT * FROM sample1"
cursor.execute(query)
records = cursor.fetchall()

########  LIST ALL THE COLUMNS ######### 
field_names = [i[0] for i in cursor.description]

#Creating list with column name
for col in field_names:
    exec(col + "=[]")

#appending records into list
for record in records:
    first_name.append(record[0])
    last_name.append(record[1])
    full_name.append(record[2])

If I need to add a new column in future, Again I have to add "abc.append(record[3])".

Is there any way to create the list and append data into it on the fly?

Thanks

0 Answers