Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
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'

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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!

over 4 years ago · Santiago Trujillo Report

0

SHOW COLUMNS FROM your-database-name.your-table-name

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!