In order to read data from SQL server to python, you need the library pyodbc.
This library can be installed using below command on jupyter notebook. This command can also be executed in command prompt without the exclamation “!”.
|
1 2 |
# installing the library to connect to sql server !pip install pyodbc |
Reading data from SQL server is a two step process listed below:
- Establishing Connection: A connection object is created using the function pyodbc.connect() by specifying the database credentials which are needed to login.
- SQL Query: Running any valid sql query using the connection object defined above and the pandas function read_sql_query()
Below snippet shows how to connect to a sample SQL server, please change the database and table details as per your system.
|
1 2 3 4 5 6 7 8 9 10 11 |
# Reading data from a SQL-SERVER/Oracle database import pyodbc import pandas as pd # Defining the connection string conn = pyodbc.connect('''DRIVER={SQL Server}; Server=127.0.0.1; UID=adminUser; PWD=passWrd@123; DataBase=PROD_AZ''') # Fetching the data from the selected table using SQL query RawData= pd.read_sql_query('''select * from [EMP].[Employee_table]''', conn) RawData.head() |
Sample Output:

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

i tried your above code but it gives error for pd.
Same error, ‘pd’ is not defined. Any help is appreciated.
Hi Bler!
Please add the below command
import pandas as pd
I have updated this post!
Thank you for the question.
Hello Faruk, thank you for your great work. Very simplified and easy to understand. I was hoping to connect with you. I need help with a project if it does not bother you. Let me know so I can share my email with you please. Thank you!