7

How can I add the columns names from sql query to pandas dataframe. I'm doing the following, but columns=columns doesn't work in my case.

import pymssql
import pandas as pd


con = pymssql.connect(
     server="MSSQLSERVER",
     port="1433",
     user="us",
     password="pass",
     database="loc")

cur = conn.cursor()

cur.execute("SELECT id from ide")

data=cur.fetchall()

pandas=pd.DataFrame(data)

cur.close()
con.close()

So when I print "pandas" it turns out to be without headers. So how can I receive them?

3
  • Look into read_sql_table: pandas.pydata.org/pandas-docs/stable/generated/… Commented Jul 13, 2016 at 13:37
  • 1
    hey guys, read sql dont work in my case-please other suggestions Commented Jul 13, 2016 at 13:46
  • I have added a comment let me know if it worked Commented Jul 13, 2016 at 14:08

2 Answers 2

13

I've also found adding as_dict=True to the cursor object works:

cur = conn.cursor(as_dict=True)

Then you can run the rest as you have it:

cur.execute("SELECT id from ide")
data=cur.fetchall()
pandas=pd.DataFrame(data)

and pandas will grab the column names from the dictionary

Sign up to request clarification or add additional context in comments.

2 Comments

Which one is better? pymssql or pyodbc? Using pyodbc, I found a lot of difficulty when using it through AWS Lambda.
pymssql works well now
3

First establish the connection: I saw you used MSSQL

import pyodbc
# Parameters
server = 'server_name'
db = 'db_name'

# Create the connection
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + db + ';Trusted_Connection=yes')

Then use pandas:

df = pandas.read_sql(sql, conn)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.