How to Access & Use SQL Database with pyodbc in Python

Installing and Importing the library pyodbc

Wen will use pyodbc library to connect python with SQL.

Install pyodbc using pip command.

pip install pyodbc

and then import the library in your Jupyter notebook

import pyodbc

pyodbc is primary job is to work as bridge between python SQL. 

In this article I am working with MS SQL but we can use the same code for other ODBC compliant database only the process of connection will vary a liitle.I


  • For Trusted Connection:
connection_string = ("Driver={SQL Server Native Client 11.0};"
            "Server=Your_Server_Name;"
            "Database=My_Database_Name;"
            "Trusted_Connection=yes;")
  • For Non-Trusted Connection:
connection_string = ("Driver={SQL Server Native Client 11.0};"
            "Server=Your_Server_Name;"
            "Database=My_Database_Name;"
            "UID=Your_User_ID;"
            "PWD=Your_Password;")

You need the following to access:

  • Server
  • Database
  • User ID
  • Password


Initialize the connection by calling pyodbc.connect function as below

connection = pyodbc.connect(connection_string)

Run the Query in SQL from Python

Need to define the cursor to do. 


# Initialise the Cursor
cursor = connection.cursor()
# Executing a SQL Query
cursor.execute('SELECT TOP(10) * FROM OINV')
for row in cursor:
    print(row)


(1, 10210, datetime.datetime(2021, 12, 1, 0, 0))
(2, 10211, datetime.datetime(2021, 12, 1, 0, 0))
(3, 10212, datetime.datetime(2021, 12, 1, 0, 0))
(4, 10213, datetime.datetime(2021, 12, 1, 0, 0))
(5, 10214, datetime.datetime(2021, 12, 1, 0, 0))
(6, 10215, datetime.datetime(2021, 12, 1, 0, 0))
(7, 110087, datetime.datetime(2021, 12, 1, 0, 0))
(8, 110088, datetime.datetime(2021, 12, 1, 0, 0))
(9, 110089, datetime.datetime(2021, 12, 1, 0, 0))
(10, 110090, datetime.datetime(2021, 12, 1, 0, 0))