Skip to content
Advertisement

How to get column names from a SQL query?

I need to put data from the SQL query into a Pandas dataframe. Please tell me is it possible to get column names the query results? I found that there is a keys() function in sqlalchemy for that but it does not work for me:

import mysql.connector
import pandas as pd

mydb = mysql.connector.connect(
  host="SQLServer",
  user="sqlusr",
  password="usrpasswd",
  database="sqldb"
)

cursor = mydb.cursor()

Query="SELECT Title, Review, Rate FROM reviews;"
cursor.execute(Query)

df = pd.DataFrame(cursor.fetchall())
df.columns = cursor.keys()

AttributeError: ‘CMySQLCursor’ object has no attribute ‘keys’

Advertisement

Answer

I think that it your are searching for

cnx = mysql.connector.connect(user=DB_USER, password=DB_USER_PASSWORD, host=DB_HOST, database=DB_NAME)
cursor = cnx.cursor()
query = ("SELECT `name`, `ftp_name`, `created_at`, `status` AS `status_customer` FROM `customers"
         "WHERE `status` = %(status)s")

cursor.execute(query, { 'status': 1 })

# cursor.description will give you a tuple of tuples where [0] for each is the column header.

num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]

print(num_fields)

print(field_names)

>>> 4
>>> [u'name', u'ftp_name', 'created_at', u'status_customer']

# OR just use this cursor function:

print(cursor.column_names)

>>> (u'name', u'ftp_name', 'created_at', u'status_customer')

Hope this helps!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement