How to get the data from MSSQL Server using Python pandas dataframe?

Today lesson is how we will get the data from MSSQL Server. We are using python (Latest: Python 3.8.2), pyodbc and pandas plugins to achieve this. If you are not sure how to install the Python and plugins, check my previous post.

1. Download and install pandas and pyodbc libraries

$ pip install pandas
$ pip install pyodbc

2. Get the first 10 records of the result:

# importing the pandas and pyodbc libraries
import pandas as pd
import pyodbc
# connect to MSSQL DB
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};
                            SERVER=SQLEXPRESS;
                            DATABASE=TEST;
                            UID=sa;
                            PWD=sa;') 
# query first 10 records data 
query = "SELECT [Column1],[Column2],[Column3]"
df = pd.read_sql(query, conn)
df.head(10)
# close DB connection
conn.close()

That’s it. I hope this will help. 🙂
Photo: https://www.brandeps.com

Leave a Reply

Your email address will not be published. Required fields are marked *