Skip to content

Latest commit

 

History

History
282 lines (194 loc) · 8.99 KB

File metadata and controls

282 lines (194 loc) · 8.99 KB
title Quickstart: Python SQL Driver - pyodbc
description This quickstart describes installing Python, and pyodbc then shows how to connect to and interact with a SQL database.
author dlevy-msft-sql
ms.author dlevy
ms.reviewer vanto, randolphwest
ms.date 07/10/2025
ms.service sql
ms.subservice connectivity
ms.topic quickstart-sdk
ms.custom
sfi-ropc-nochange

Quickstart: Connect with the pyodbc driver for Python

In this quickstart, you connect a Python script to a database that you created and loaded with sample data. You use the pyodbc driver for Python to connect to your database and perform basic operations, like reading and writing data.

pyodbc documentation | pyodbc source code | Package (PyPi)

Prerequisites

Setting up

Follow these steps to configure your development environment to develop an application using the pyodbc Python driver.

Note

This driver uses the Tabular Data Stream (TDS) protocol, which is enabled by default in SQL Server, SQL database in Fabric and Azure SQL Database. No extra configuration is required.

Install the pyodbc package

Get the pyodbc package from PyPI.

  1. Open a command prompt in an empty directory.

  2. Install the pyodbc package.

    pip install pyodbc

Install python-dotenv package

Get the python-dotenv from PyPI.

  1. In the same directory, install the python-dotenv package.

    pip install python-dotenv

Check installed packages

You can use the PyPI command-line tool to verify that your intended packages are installed.

  1. Check the list of installed packages with pip list.

    pip list

Create a SQL database

This quickstart requires the [!INCLUDE sssampledbnormal-md] Lightweight schema, on Microsoft SQL Server, SQL database in Fabric or Azure SQL Database.

Create a SQL database in minutes using the Azure portal

Copy the ODBC connection string from the Connection strings tab.

Load AdventureWorks sample data in your SQL database in Microsoft Fabric

Copy the ODBC connection string from the Settings tab.

AdventureWorks sample databases


Run the code

Create a new file

  1. Create a new file named app.py.

  2. Add a module docstring.

    """
    Connects to a SQL database using pyodbc
    """
  3. Import the pyodbc package.

    from os import getenv
    from dotenv import load_dotenv
    from pyodbc import connect
  4. Use the pyodbc.connect function to connect to a SQL database.

    load_dotenv()
    conn = connect(getenv("SQL_CONNECTION_STRING"))
  5. In the current directory, create a new file named .env.

  6. Within the .env file, add an entry for your connection string named SQL_CONNECTION_STRING. Replace the example here with your actual connection string value.

    SQL_CONNECTION_STRING="Driver={ODBC Driver 18 for SQL Server};Server=<server_name>;Database={<database_name>};Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryInteractive"
    

    [!TIP]
    The connection string used here largely depends on the type of SQL database you're connecting to. If you're connecting to an Azure SQL Database or a SQL database in Fabric, use the ODBC connection string from the connection strings tab. You might need to adjust the authentication type depending on your scenario. For more information on connection strings and their syntax, see connection string syntax reference.

Execute a query

Use a SQL query string to execute a query and parse the results.

  1. Create a variable for the SQL query string.

    SQL_QUERY = """
    SELECT
    TOP 5 c.CustomerID,
    c.CompanyName,
    COUNT(soh.SalesOrderID) AS OrderCount
    FROM
    SalesLT.Customer AS c
    LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID
    GROUP BY
    c.CustomerID,
    c.CompanyName
    ORDER BY
    OrderCount DESC;
    """
  2. Use cursor.execute to retrieve a result set from a query against the database.

    cursor = conn.cursor()
    cursor.execute(SQL_QUERY)

    [!NOTE]
    This function essentially accepts any query and returns a result set, which can be iterated over with the use of cursor.fetchone().

  3. Use cursor.fetchall with a foreach loop to get all the records from the database. Then print the records.

    records = cursor.fetchall()
    for r in records:
        print(f"{r.CustomerID}\t{r.OrderCount}\t{r.CompanyName}")
  4. Save the app.py file.

  5. Open a terminal and test the application.

    python app.py

    Here's the expected output.

    29485   1       Professional Sales and Service
    29531   1       Remarkable Bike Store
    29546   1       Bulk Discount Store
    29568   1       Coalition Bike Company
    29584   1       Futuristic Bikes
    

Insert a row as a transaction

Execute an INSERT statement safely and pass parameters. Passing parameters as values protects your application from SQL injection attacks.

  1. Add an import for randrange from the random library to the top of app.py.

    from random import randrange
  2. At the end of app.py add code to generate a random product number.

    productNumber = randrange(1000)

    [!TIP]
    Generating a random product number here ensures that you can run this sample multiple times.

  3. Create a SQL statement string.

    SQL_STATEMENT = """
    INSERT SalesLT.Product (
    Name,
    ProductNumber,
    StandardCost,
    ListPrice,
    SellStartDate
    ) OUTPUT INSERTED.ProductID
    VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
    """
  4. Execute the statement using cursor.execute.

    cursor.execute(
        SQL_STATEMENT,
        (
            f'Example Product {productNumber}',
            f'EXAMPLE-{productNumber}',
            100,
            200
        )
    )
  5. Fetch the first column of the single result using cursor.fetchval, print the result's unique identifier, and then commit the operation as a transaction using connection.commit.

    resultId = cursor.fetchval()
    print(f"Inserted Product ID : {resultId}")
    conn.commit()

    [!TIP]
    Optionally, you can use connection.rollback to roll back the transaction.

  6. Close the cursor and connection using cursor.close and connection.close.

    cursor.close()
    conn.close()
  7. Save the app.py file and test the application again.

    python app.py

    Here's the expected output.

    Inserted Product ID : 1001
    

Next step

Visit the pyodbc driver GitHub repository for more examples, to contribute ideas or report issues.

[!div class="nextstepaction"] pyodbc driver on GitHub