Python Program to get column names and values of a table using MySQL

In this program, you will learn how to get column names and values of a table using Python and MySQL.


cur.execute("select * from emp")
result = cur.fetchall()
num_fields = len(cur.description)
field_names = [i[0] for i in cur.description]
print(field_names)

Python Program to get column names and values of a table using MySQL

Example: How to get column names and values of a table using Python and MySQL

import mysql.connector

myconn = mysql.connector.connect(host="localhost", user="root", passwd="12345678", database="xiith")
cur = myconn.cursor()

try:
    cur.execute("select * from emp")
    result = cur.fetchall()
    num_fields = len(cur.description)
    field_names = [i[0] for i in cur.description]
    print(field_names)

    for value in result:
        print(value)

    myconn.commit()
except:
    myconn.rollback()
myconn.close()

Output:

['id', 'name', 'salary']
('101', 'John', 40000)
('102', 'Mike', 40000)