Skip to content

Commit d3e03ca

Browse files
Convert remaining pyodbc samples to mssql-python (batch 2) (#36550)
* Convert remaining pyodbc samples to mssql-python (batch 2) Data Exploration Series (3 files): - python-dataframe-pandas.md: Updated to use mssql-python for reading SQL into pandas - python-dataframe-sql-server.md: Updated to use mssql-python for inserting DataFrame into SQL - python-plot-histogram.md: Replaced pyodbc/SQLAlchemy with direct mssql-python Kubernetes Tutorial: - develop-kubernetes-application.md: Updated Flask app to use mssql-python, updated Dockerfile from laudio/pyodbc to python:3.10-slim with ODBC driver install Reference Pages: - connect-query-content-reference-guide.md: Added mssql-python as recommended Python driver - sql-server-linux-develop-connectivity-libraries.md: Added mssql-python to driver list * Add Azure CLI and Fabric SQL database tabs to Python quickstart - Add ActiveDirectoryAzCli tab as recommended auth for local dev (faster than Default) - Add Fabric SQL database tab showing connection to SQL database in Fabric - Emphasize az login works on Windows, macOS, and Linux - Update prerequisites to mention Fabric as alternative database option * Fix auth methods: use ActiveDirectoryDefault (recommended), add Fabric SQL tab with platform guidance * Remove PR description from tracking * Add mssql-python platform prereqs include for macOS/Linux * Simplify Python driver to mssql-python only in reference guide * Simplify Python driver to mssql-python only in Linux connectivity libraries * Remove PyODBC tab from vector data type, keep mssql-python only * Add platform-specific prereqs to Azure SQL Python quickstart * Inline platform prereqs in Azure SQL Python quickstart * Replace conflicting tabs with note linking to prereqs * Apply suggestions from code review Co-authored-by: Van To <40007119+VanMSFT@users.noreply.github.com> --------- Co-authored-by: Van To <40007119+VanMSFT@users.noreply.github.com>
1 parent a493e57 commit d3e03ca

11 files changed

Lines changed: 196 additions & 131 deletions

azure-sql/database/azure-sql-python-quickstart.md

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ This quickstart describes how to connect an application to a database in Azure S
2525
## Prerequisites
2626

2727
- An [Azure subscription](https://azure.microsoft.com/pricing/purchase-options/azure-account?icid=azurefreeaccountpython/).
28-
- An Azure SQL database configured with Microsoft Entra authentication. You can create one using the [Quickstart: Create a single database - Azure SQL Database](single-database-create-quickstart.md).
28+
- An Azure SQL database configured with Microsoft Entra authentication. You can create one using the [Quickstart: Create a single database - Azure SQL Database](single-database-create-quickstart.md). Alternatively, you can use a [SQL database in Microsoft Fabric](/fabric/database/sql/create).
2929
- Visual Studio Code with the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
3030
- Python 3.10 or later.
31-
- The [Azure CLI](/cli/azure/install-azure-cli) (required for `ActiveDirectoryDefault` authentication).
31+
- The [Azure CLI](/cli/azure/install-azure-cli) for passwordless authentication (works on Windows, macOS, and Linux).
3232

3333
## Configure the database
3434

@@ -69,7 +69,8 @@ Create a new Python project using Visual Studio Code.
6969
7070
To connect to Azure SQL Database using Python, install the `mssql-python` driver. This driver has built-in support for Microsoft Entra authentication, eliminating the need for manual token handling. In this quickstart, you also install `fastapi`, `uvicorn`, and `pydantic` packages to create and run an API.
7171
72-
For details and specific instructions for installing the `mssql-python` driver, see [mssql-python installation guide](https://github.com/microsoft/mssql-python/wiki/Installation).
72+
> [!NOTE]
73+
> On macOS and Linux, system dependencies are required before installing `mssql-python`. See [Install the mssql-python package](/sql/connect/python/mssql-python/python-sql-driver-mssql-python-quickstart#install-the-mssql-python-package) for platform-specific instructions.
7374
7475
1. Create a *requirements.txt* file with the following lines:
7576
@@ -97,16 +98,31 @@ For local development, create a `.env` file in your project folder to store your
9798
9899
The mssql-python driver has built-in support for Microsoft Entra authentication. Use the `Authentication` parameter to specify the authentication method.
99100
100-
## [ActiveDirectoryDefault](#tab/sql-default)
101+
## [ActiveDirectoryDefault (Recommended)](#tab/sql-default)
101102
102-
`ActiveDirectoryDefault` automatically discovers credentials from multiple sources (Visual Studio Code, Azure CLI, environment variables, etc.) without requiring interactive login. This method is convenient for local development but slower due to credential discovery.
103+
`ActiveDirectoryDefault` automatically discovers credentials from multiple sources without requiring interactive login. This is the **recommended option for local development**.
104+
105+
For the most reliable local development experience, sign in with Azure CLI first:
106+
107+
```bash
108+
az login
109+
```
110+
111+
Then use this connection string format in your `.env` file:
103112

104113
```text
105114
AZURE_SQL_CONNECTIONSTRING=Server=<database-server-name>.database.windows.net;Database=<database-name>;Authentication=ActiveDirectoryDefault;Encrypt=yes;TrustServerCertificate=no;
106115
```
107116

108-
> [!IMPORTANT]
109-
> `ActiveDirectoryDefault` is intended for local development only. It tries multiple authentication methods in sequence (environment variables, managed identity, Azure CLI, Visual Studio, etc.), which adds latency. For production applications, use the specific authentication method for your scenario:
117+
`ActiveDirectoryDefault` evaluates credentials in the following order:
118+
1. **Environment variables** (for service principal credentials)
119+
1. **Managed identity** (when running on Azure)
120+
1. **Azure CLI** (from `az login`)
121+
1. **Visual Studio** (Windows only)
122+
1. **Azure PowerShell** (from `Connect-AzAccount`)
123+
124+
> [!TIP]
125+
> For production applications, use the specific authentication method for your scenario to avoid credential discovery latency:
110126
> - **Azure App Service/Functions**: Use `ActiveDirectoryMSI` (managed identity)
111127
> - **Interactive user login**: Use `ActiveDirectoryInteractive`
112128
> - **Service principal**: Use `ActiveDirectoryServicePrincipal`
@@ -130,6 +146,24 @@ AZURE_SQL_CONNECTIONSTRING=Server=<database-server-name>.database.windows.net;Da
130146
> [!WARNING]
131147
> Use caution when managing connection strings that contain secrets such as usernames, passwords, or access keys. These secrets shouldn't be committed to source control or placed in unsecure locations where they might be accessed by unintended users. Add `.env` to your `.gitignore` file to prevent accidentally committing secrets.
132148
149+
## [Fabric SQL Database](#tab/sql-fabric)
150+
151+
To connect to a [SQL database in Microsoft Fabric](/fabric/database/sql/overview), use the same authentication methods. The server name follows the Fabric format.
152+
153+
On **Windows domain-joined machines**, use `ActiveDirectoryIntegrated` for seamless authentication with no extra steps:
154+
155+
```text
156+
AZURE_SQL_CONNECTIONSTRING=Server=<workspace-guid>.database.fabric.microsoft.com,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryIntegrated;
157+
```
158+
159+
On **macOS, Linux, or non-domain Windows**, use `ActiveDirectoryDefault` after signing in with Azure CLI (`az login`):
160+
161+
```text
162+
AZURE_SQL_CONNECTIONSTRING=Server=<workspace-guid>.database.fabric.microsoft.com,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryDefault;
163+
```
164+
165+
You can find your Fabric SQL database connection string in the Fabric portal under your database's settings.
166+
133167
---
134168

135169
You can get the details to create your connection string from the Azure portal:
@@ -187,7 +221,7 @@ def root():
187221
conn.commit()
188222
conn.close()
189223
except Exception as e:
190-
# Table may already exist
224+
# Table might already exist
191225
print(e)
192226
return "Person API"
193227

azure-sql/database/connect-query-content-reference-guide.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ The following table lists connectivity libraries or *drivers* that client applic
9494
| **Java** | Windows, Linux, macOS | [Microsoft JDBC driver for SQL Server](/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server/) | [Download](/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server) |
9595
| **Node.js** | Windows, Linux, macOS | [Node.js driver for SQL Server](/sql/connect/node-js/node-js-driver-for-sql-server/) | [Install](/sql/connect/node-js/step-1-configure-development-environment-for-node-js-development/) |
9696
| **PHP** | Windows, Linux, macOS | [Microsoft Drivers for PHP for SQL Server](/sql/connect/php/microsoft-php-driver-for-sql-server) | [Download](/sql/connect/php/download-drivers-php-sql-server) |
97-
| **Python** | Windows, Linux, macOS | [Python SQL driver](/sql/connect/python/python-driver-for-sql-server/) | Install choices:<br />- [pymssql](/sql/connect/python/pymssql/step-1-configure-development-environment-for-pymssql-python-development/)<br />- [pyodbc](/sql/connect/python/pyodbc/step-1-configure-development-environment-for-pyodbc-python-development/) |
97+
| **Python** | Windows, Linux, macOS | [mssql-python](/sql/connect/python/mssql-python/python-sql-driver-mssql-python) | [Install](/sql/connect/python/mssql-python/python-sql-driver-mssql-python-quickstart#install-the-mssql-python-package) |
9898
| **Ruby** | Windows, Linux, macOS | [Ruby driver for SQL Server](/sql/connect/ruby/ruby-driver-for-sql-server/) | [Install](/sql/connect/ruby/step-1-configure-development-environment-for-ruby-development/) |
9999

100100
### Data-access frameworks

azure-sql/database/develop-kubernetes-application.md

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ titleSuffix: Azure SQL Database
44
description: Learn how to develop a modern application using Python, Docker Containers, Kubernetes, and Azure SQL Database.
55
author: rwestMSFT
66
ms.author: randolphwest
7-
ms.reviewer: wiassaf, damauri, mathoma
8-
ms.date: 06/13/2025
7+
ms.reviewer: wiassaf, damauri, mathoma, dlevy
8+
ms.date: 02/03/2026
99
ms.service: azure-sql-database
1010
ms.subservice: development
1111
ms.topic: tutorial
@@ -65,15 +65,14 @@ Throughout this article, there are several values you should replace. Ensure tha
6565
- `ReplaceWith_AzureContainerRegistryName`: Replace this value with the name of the Azure Container Registry you would like to create.
6666
- `ReplaceWith_AzureKubernetesServiceName`: Replace this value with the name of the Azure Kubernetes Service you would like to create.
6767

68-
The developers at AdventureWorks use a mix of Windows, Linux, and Apple systems for development, so they are using [Visual Studio Code](https://code.visualstudio.com/Download) as their environment and git for the source control, both of which run cross-platform.
68+
The developers at AdventureWorks use a mix of Windows, Linux, and Apple systems for development, so they're using [Visual Studio Code](https://code.visualstudio.com/Download) as their environment and git for the source control, both of which run cross-platform.
6969

7070
For the PoC, the team requires the following prerequisites:
7171

72-
1. **Python, pip, and packages** - The development team chooses the [Python programming language](/training/paths/beginner-python/) as the standard for this web-based application. Currently they are using version 3.9, but any version supporting the PoC required packages is acceptable.
73-
- You can [download Python version 3.9](https://www.python.org/downloads/release/python-390/) from python.org.
74-
1. The team is using the `pyodbc` package for database access.
75-
- You can [install the pyodbc package with *pip* commands](https://pypi.org/project/pyodbc/).
76-
- You might also need the [Microsoft ODBC Driver software](/sql/connect/odbc/download-odbc-driver-for-sql-server?view=azuresqldb-current&preserve-view=true) if you do not have it installed already.
72+
1. **Python, pip, and packages** - The development team chooses the [Python programming language](/training/paths/beginner-python/) as the standard for this web-based application. Currently they're using version 3.10, but any version supporting the PoC required packages is acceptable.
73+
- You can [download Python version 3.10](https://www.python.org/downloads/) from python.org.
74+
1. The team is using the `mssql-python` driver for database access.
75+
- You can [install the mssql-python driver with *pip* commands](https://pypi.org/project/mssql-python/).
7776
1. The team is using the `ConfigParser` package for controlling and setting configuration variables.
7877
- You can [install the configparser package with *pip* commands](https://pypi.org/project/configparser/).
7978
1. The team is using the *Flask package* for a web interface for the application.
@@ -151,20 +150,21 @@ Next, the Development team created a simple Python application that opens a conn
151150
1. Set up the libraries for the configuration and base web interfaces.
152151
1. Load the variables from the `.env` file.
153152
1. Create the Flask-RESTful Application.
154-
1. Get to Azure SQL Database connection information using the `config.ini` file values.
155-
1. Create connection to Azure SQL Database using the `config.ini` file values.
156-
1. Connect to Azure SQL Database using the `pyodbc` package.
153+
1. Get to Azure SQL Database connection information using the `.env` file values.
154+
1. Connect to Azure SQL Database using the `mssql-python` driver.
157155
1. Create the SQL query to run against the database.
158156
1. Create the class used to return the data from the API.
159157
1. Set the API endpoint to the `Products` class.
160158
1. Finally, start the app on default Flask port 5000.
161159

162160
```python
163161
# Set up the libraries for the configuration and base web interfaces
162+
import os
163+
import json
164164
from dotenv import load_dotenv
165165
from flask import Flask
166166
from flask_restful import Resource, Api
167-
import pyodbc
167+
from mssql_python import connect
168168

169169
# Load the variables from the .env file
170170
load_dotenv()
@@ -173,22 +173,17 @@ Next, the Development team created a simple Python application that opens a conn
173173
app = Flask(__name__)
174174
api = Api(app)
175175

176-
# Get to Azure SQL Database connection information using the config.ini file values
176+
# Get to Azure SQL Database connection information using the .env file values
177177
server_name = os.getenv('SQL_SERVER_ENDPOINT')
178178
database_name = os.getenv('SQL_SERVER_DATABASE')
179179
user_name = os.getenv('SQL_SERVER_USERNAME')
180180
password = os.getenv('SQL_SERVER_PASSWORD')
181181

182-
# Create connection to Azure SQL Database using the config.ini file values
183-
ServerName = config.get('Connection', 'SQL_SERVER_ENDPOINT')
184-
DatabaseName = config.get('Connection', 'SQL_SERVER_DATABASE')
185-
UserName = config.get('Connection', 'SQL_SERVER_USERNAME')
186-
PasswordValue = config.get('Connection', 'SQL_SERVER_PASSWORD')
182+
# Create connection string for mssql-python
183+
connection_string = f'Server={server_name};Database={database_name};UID={user_name};PWD={password};Encrypt=yes;TrustServerCertificate=no;'
187184

188-
# Connect to Azure SQL Database using the pyodbc package
189-
# Note: You may need to install the ODBC driver if it is not already there. You can find that at:
190-
# https://learn.microsoft.com/sql/connect/odbc/download-odbc-driver-for-sql-server
191-
connection = pyodbc.connect(f'Driver=ODBC Driver 17 for SQL Server;Server={ServerName};Database={DatabaseName};uid={UserName};pwd={PasswordValue}')
185+
# Connect to Azure SQL Database using the mssql-python driver
186+
connection = connect(connection_string)
192187

193188
# Create the SQL query to run against the database
194189
def query_db():
@@ -218,7 +213,7 @@ Next, the Development team created a simple Python application that opens a conn
218213
:::image type="content" source="media/develop-kubernetes-application/api-return-page-localhost-products.png" alt-text="Screenshot from a web browser of the Flask return page." lightbox="media/develop-kubernetes-application/api-return-page-localhost-products.png":::
219214

220215
> [!IMPORTANT]
221-
> When building production applications, do not use the administrator account to access the database. For more information, read more about [how to set up an account for your application](https://devblogs.microsoft.com/azure-sql/create-and-connect-to-an-azure-sql-db/). The code in this article is simplified so that you can quickly get started with applications using Python and Kubernetes in Azure.
216+
> When building production applications, don't use the administrator account to access the database. For more information, read more about [how to set up an account for your application](https://devblogs.microsoft.com/azure-sql/create-and-connect-to-an-azure-sql-db/). The code in this article is simplified so that you can quickly get started with applications using Python and Kubernetes in Azure.
222217
>
223218
> More realistically, you could use a [contained database user](/sql/relational-databases/security/contained-database-users-making-your-database-portable?view=azuresqldb-current&preserve-view=true) with read-only permissions, or a login or contained database user connected to [a user-assigned managed identity](authentication-azure-ad-user-assigned-managed-identity.md) with read-only permissions.
224219
>
@@ -228,12 +223,11 @@ Next, the Development team created a simple Python application that opens a conn
228223

229224
A Container is a reserved, protected space in a computing system that provides isolation and encapsulation. To create a container, use a Manifest file, which is simply a text file describing the binaries and code you wish to contain. Using a Container Runtime (such as Docker), you can then create a binary image that has all of the files you want to run and reference. From there, you can "run" the binary image, the Container, which you can reference as if it were a full computing system. It's a smaller, simpler way to abstract your application runtimes and environment than using a full virtual machine. For more information, see [Containers and Docker](/dotnet/architecture/microservices/container-docker-introduction/docker-defined).
230225

231-
The team started with a DockerFile (the Manifest) that layers the elements of what the team wants to use. They start with a base Python image that already has the `pyodbc`
232-
libraries installed, and then they run all commands necessary to contain the program and config file in the previous step.
226+
The team started with a DockerFile (the Manifest) that layers the elements of what the team wants to use. They start with a base Python image, and then they run all commands necessary to contain the program and config file in the previous step.
233227

234228
The following Dockerfile has the following steps:
235229

236-
1. Start with a Container binary that already has Python and `pyodbc` installed.
230+
1. Start with a Container binary that has Python installed.
237231
1. Create a Working directory for the application.
238232
1. Copy all of the code from the current directory into the `WORKDIR`.
239233
1. Install the libraries that are required.
@@ -242,8 +236,17 @@ The following Dockerfile has the following steps:
242236
```dockerfile
243237
# syntax=docker/dockerfile:1
244238

245-
# Start with a Container binary that already has Python and pyodbc installed
246-
FROM laudio/pyodbc
239+
# Start with a Container binary that has Python installed
240+
FROM python:3.10-slim
241+
242+
# Install ODBC driver (required by mssql-python)
243+
RUN apt-get update && apt-get install -y \
244+
curl gnupg2 apt-transport-https \
245+
&& curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
246+
&& curl https://packages.microsoft.com/config/debian/11/prod.list > /etc/apt/sources.list.d/mssql-release.list \
247+
&& apt-get update \
248+
&& ACCEPT_EULA=Y apt-get install -y msodbcsql18 unixodbc-dev \
249+
&& rm -rf /var/lib/apt/lists/*
247250

248251
# Create a Working directory for the application
249252
WORKDIR /flask2sql
@@ -439,6 +442,6 @@ del c:\users\ReplaceWith_YourUserName\.kube\config
439442
## Related content
440443

441444
- [Application development overview - SQL Database & SQL Managed Instance](develop-overview.md?view=azuresqldb-current&preserve-view=true)
442-
- [Connect to and query Azure SQL Database using Python and the pyodbc driver](azure-sql-python-quickstart.md?view=azuresqldb-current&preserve-view=true&tabs=windows%2Csql-inter)
445+
- [Connect to and query Azure SQL Database using Python and the mssql-python driver](azure-sql-python-quickstart.md?view=azuresqldb-current&preserve-view=true)
443446
- [What are Dev Container Templates for Azure SQL Database?](local-dev-experience-dev-containers.md)
444447
- [Browse code samples for Azure SQL Database](/samples/browse/?products=azure-sql-database%2Cazure-sql-managed-instance%2Cazure-sqlserver-vm&expanded=azure)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
---
2+
author: dlevy-msft-sql
3+
ms.author: dlevy
4+
ms.date: 02/05/2026
5+
ms.service: sql
6+
ms.topic: include
7+
---
8+
### [Windows](#tab/windows)
9+
10+
```console
11+
pip install mssql-python
12+
```
13+
14+
### [Alpine](#tab/alpine-linux)
15+
16+
```console
17+
apk add libtool krb5-libs krb5-dev
18+
pip install mssql-python
19+
```
20+
21+
### [Debian/Ubuntu](#tab/debianUbuntu-linux)
22+
23+
```console
24+
apt-get install -y libltdl7 libkrb5-3 libgssapi-krb5-2
25+
pip install mssql-python
26+
```
27+
28+
### [RHEL](#tab/RHEL-linux)
29+
30+
```console
31+
dnf install -y libtool-ltdl krb5-libs
32+
pip install mssql-python
33+
```
34+
35+
### [SUSE](#tab/SUSE-linux)
36+
37+
```console
38+
zypper install -y libltdl7 libkrb5-3 libgssapi-krb5-2
39+
pip install mssql-python
40+
```
41+
42+
### [openSUSE](#tab/openSUSE-linux)
43+
44+
```console
45+
zypper install -y libltdl7
46+
pip install mssql-python
47+
```
48+
49+
### [macOS](#tab/mac)
50+
51+
```console
52+
brew install openssl
53+
pip install mssql-python
54+
```
55+
56+
---

0 commit comments

Comments
 (0)