Skip to content

Commit 90572bb

Browse files
Convert Python samples from pyodbc to mssql-python
Replace pyodbc with mssql-python driver in all Python code samples: - azure-sql/database/azure-sql-python-quickstart.md: Full FastAPI rewrite with mssql-python - azure-sql/database/azure-sql-passwordless-migration-python.md: Simplified passwordless auth - docs/machine-learning/tutorials: Updated 5 tutorial files - docs/machine-learning/python/setup-python-client-tools-sql.md: Updated driver setup - docs/sql-server/connect-to-database-engine.md: Updated Python driver link - docs/relational-databases/security/networking/tds-8.md: Updated TDS 8.0 examples - azure-sql/toc.yml: Updated nav text mssql-python provides built-in Microsoft Entra authentication without requiring azure-identity or complex token handling code.
1 parent eb153ab commit 90572bb

11 files changed

Lines changed: 106 additions & 94 deletions

azure-sql/database/azure-sql-passwordless-migration-python.md

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ title: Migrate a Python Application to Use Passwordless Connections
33
description: Learn how to migrate a Python application to use passwordless connections with Azure SQL Database.
44
author: WilliamDAssafMSFT
55
ms.author: wiassaf
6-
ms.reviewer: rotabor, mathoma
7-
ms.date: 06/13/2025
6+
ms.reviewer: dlevy, rotabor, mathoma
7+
ms.date: 01/29/2026
88
ms.service: azure-sql-database
99
ms.subservice: security
1010
ms.topic: how-to
@@ -23,6 +23,8 @@ ms.custom:
2323

2424
Application requests to Azure SQL Database must be authenticated. Although there are multiple options for authenticating to Azure SQL Database, you should prioritize passwordless connections in your applications when possible. Traditional authentication methods that use passwords or secret keys create security risks and complications. Visit the [passwordless connections for Azure services](/azure/developer/intro/passwordless-overview) hub to learn more about the advantages of moving to passwordless connections. The following tutorial explains how to migrate an existing Python application to connect to Azure SQL Database to use passwordless connections instead of a username and password solution.
2525

26+
The [mssql-python](/sql/connect/python/mssql-python/python-sql-driver-mssql-python) driver provides built-in support for Microsoft Entra authentication, making passwordless connections straightforward with minimal code changes.
27+
2628
## Configure the Azure SQL Database
2729

2830
[!INCLUDE [configure-the-azure-sql-database](../includes/passwordless/configure-the-azure-sql-database.md)]
@@ -43,40 +45,36 @@ Create a user in Azure SQL Database. The user should correspond to the Azure acc
4345

4446
### Update the local connection configuration
4547

46-
Existing application code that connects to Azure SQL Database using the [Python SQL Driver - pyodbc](/sql/connect/python/pyodbc/python-sql-driver-pyodbc) continues to work with passwordless connections with minor changes. For example, the following code works with both SQL authentication and passwordless connections when running locally and when deployed to Azure App Service.
48+
Migrating to passwordless connections with [mssql-python](/sql/connect/python/mssql-python/python-sql-driver-mssql-python) requires only a connection string change. The driver has built-in support for Microsoft Entra authentication modes, eliminating the need for manual token handling.
4749

4850
```python
4951
import os
50-
import pyodbc, struct
51-
from azure.identity import DefaultAzureCredential
52+
from mssql_python import connect
5253

5354
connection_string = os.environ["AZURE_SQL_CONNECTIONSTRING"]
5455

5556
def get_all():
56-
with get_conn() as conn:
57+
with connect(connection_string) as conn:
5758
cursor = conn.cursor()
5859
cursor.execute("SELECT * FROM Persons")
5960
# Do something with the data
6061
return
61-
62-
def get_conn():
63-
credential = DefaultAzureCredential(exclude_interactive_browser_credential=False)
64-
token_bytes = credential.get_token("https://database.windows.net/.default").token.encode("UTF-16-LE")
65-
token_struct = struct.pack(f'<I{len(token_bytes)}s', len(token_bytes), token_bytes)
66-
SQL_COPT_SS_ACCESS_TOKEN = 1256 # This connection option is defined by microsoft in msodbcsql.h
67-
conn = pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct})
68-
return conn
6962
```
7063

71-
> [!TIP]
72-
> In this example code, the App Service environment variable `WEBSITE_HOSTNAME` is used to determine what environment the code is running in. For other deployment scenarios, you can use other environment variables to determine the environment.
64+
To update the referenced connection string (`AZURE_SQL_CONNECTIONSTRING`) for local development, use the passwordless connection string format with `ActiveDirectoryDefault` authentication:
7365

74-
To update the referenced connection string (`AZURE_SQL_CONNECTIONSTRING`) for local development, use the passwordless connection string format:
75-
76-
```
77-
Driver={ODBC Driver 18 for SQL Server};Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30
66+
```text
67+
Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryDefault
7868
```
7969

70+
`ActiveDirectoryDefault` automatically discovers credentials from multiple sources (Azure CLI, environment variables, Visual Studio, etc.) without requiring interactive login. This is convenient for development but adds latency as it tries each credential source in sequence.
71+
72+
> [!IMPORTANT]
73+
> `ActiveDirectoryDefault` is intended for local development only. It tries multiple authentication methods in sequence, which adds latency and can cause unexpected behavior in production. For production applications, use the specific authentication method for your scenario:
74+
> - **Azure App Service/Functions**: Use `ActiveDirectoryMSI` (managed identity)
75+
> - **Interactive user login**: Use `ActiveDirectoryInteractive`
76+
> - **Service principal**: Use `ActiveDirectoryServicePrincipal`
77+
8078
### Test the app
8179

8280
Run your app locally and verify that the connections to Azure SQL Database are working as expected. Keep in mind that it can take several minutes for changes to Azure users and roles to propagate through your Azure environment. Your application is now configured to run locally without developers having to manage secrets in the application itself.
@@ -132,12 +130,12 @@ Complete the following steps in the Azure portal to associate the user-assigned
132130

133131
### Update the connection string
134132

135-
Update your Azure app configuration to use the passwordless connection string format. The format should be the same used in your local environment.
133+
Update your Azure app configuration to use the passwordless connection string format with `ActiveDirectoryMSI` authentication for managed identity.
136134

137135
Connection strings can be stored as environment variables in your app hosting environment. The following instructions focus on App Service, but other Azure hosting services provide similar configurations.
138136

139137
```connectionstring
140-
Driver={ODBC Driver 18 for SQL Server};Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30
138+
Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryMSI
141139
```
142140

143141
`<database-server-name>` is the name of your Azure SQL Database server and `<database-name>` is the name of your Azure SQL Database.
@@ -149,16 +147,21 @@ To use the user-assigned managed identity, create an `AZURE_CLIENT_ID` environme
149147
Save your changes and restart the application if it doesn't do so automatically.
150148

151149
> [!NOTE]
152-
> The example connection code shown in this migration guide uses the [DefaultAzureCredential](/python/api/azure-identity/azure.identity.defaultazurecredential) class when deployed. Specifically, it uses the DefaultAzureCredential without passing the user-assigned managed identity client ID to the constructor. In this scenario, the fallback is to check for the AZURE_CLIENT_ID environment variable. If the AZURE_CLIENT_ID environment variable doesn't exist, a system-assigned managed identity will be used if configured.
150+
> When using a user-assigned managed identity, include the client ID in the connection string using the `User Id` parameter:
151+
>
152+
> ```connectionstring
153+
> Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryMSI;User Id=<managed-identity-client-id>
154+
> ```
153155
>
154-
> If you pass the managed identity client ID in the DefaultAzureCredential constructor, the connection code can still be used locally and deployed because the authentication process falls back to interactive authentication in the local scenario. For more information, see the [Azure Identity client library for Python](/python/api/overview/azure/identity-readme#defaultazurecredential).
156+
> If you omit the `User Id` parameter, the driver uses the system-assigned managed identity if one is configured.
155157
156158
### Test the application
157159
158160
Test your app to make sure everything is still working. It can take a few minutes for all of the changes to propagate through your Azure environment.
159161
160162
## Related content
161163
164+
- [mssql-python driver documentation](/sql/connect/python/mssql-python/python-sql-driver-mssql-python)
162165
- [Passwordless overview](/azure/developer/intro/passwordless-overview)
163166
- [Managed identity best practices](/azure/active-directory/managed-identities-azure-resources/managed-identity-best-practice-recommendations)
164167
- [Tutorial: Secure a database in Azure SQL Database](/azure/azure-sql/database/secure-database-tutorial)

0 commit comments

Comments
 (0)