Azure SQL Management Client Library
The `azure-mgmt-sql` library is the Microsoft Azure SQL Management Client Library for Python. It provides classes and methods to programmatically manage Azure SQL resources such as SQL Servers, databases, elastic pools, firewalls, and more. It is part of the Azure SDK for Python (Track 2) and is currently at version 3.0.1. Azure SDK libraries typically follow a regular release cadence with updates corresponding to Azure service API changes.
Warnings
- breaking Migration from older Azure SDK (Track 1) clients to current (Track 2) clients involves significant breaking changes in client construction, authentication, and method signatures.
- gotcha Many Azure SQL management operations are resource group-scoped. Operations like creating a server or database, or getting specific properties, require the resource group name in addition to the resource name.
- gotcha Azure SDK for Python offers both synchronous and asynchronous clients (e.g., `SqlManagementClient` vs `AsyncSqlManagementClient`). Mixing these can lead to runtime errors.
- gotcha List operations (e.g., `servers.list()`, `databases.list_by_server()`) return an iterable object (a 'pager') which needs to be iterated over to fetch all results, rather than a simple Python list.
Install
-
pip install azure-mgmt-sql azure-identity
Imports
- SqlManagementClient
from azure.mgmt.sql import SqlManagementClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.sql import SqlManagementClient
# Set your Azure Subscription ID in environment variables or replace directly
# e.g., AZURE_SUBSCRIPTION_ID = 'your-subscription-id'
subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', 'YOUR_SUBSCRIPTION_ID')
if subscription_id == 'YOUR_SUBSCRIPTION_ID':
raise ValueError("Please set the AZURE_SUBSCRIPTION_ID environment variable or replace 'YOUR_SUBSCRIPTION_ID'")
# Authenticate using DefaultAzureCredential
# This tries a series of authentication methods (environment variables, managed identity, VS Code, Azure CLI, etc.)
credential = DefaultAzureCredential()
# Create a SQL Management Client
sql_client = SqlManagementClient(credential, subscription_id)
print(f"Listing SQL Servers in subscription '{subscription_id}':")
# List all SQL Servers in the subscription
try:
sql_servers = sql_client.servers.list()
for server in sql_servers:
print(f" - Server Name: {server.name}, Location: {server.location}")
except Exception as e:
print(f"An error occurred: {e}")