Python Fetch Database Columns

We can read the specific columns by mentioning their names instead of using star (*).

In the following example, we will read the name, id, and salary from the Employee table and print it on the console.

Python Fetch Database Columns Example

import mysql.connector  
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "naveen",database = "PythonDB")  
#creating the cursor object  
cur = myconn.cursor()  
try:  
    #Reading the Employee data      
    cur.execute("select name, id, salary from Employee")  
  
    #fetching the rows from the cursor object  
    result = cur.fetchall()  
    #printing the result  
    for x in result:  
        print(x);  
except:  
    myconn.rollback()  
myconn.close()