You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Microsoft Python Driver for SQL Server - mssql-python
description
mssql-python is Microsoft's Python driver for SQL Server, Azure SQL Database, Azure SQL Managed Instance, and SQL database in Microsoft Fabric.
author
dlevy-msft-sql
ms.author
dlevy
ms.reviewer
vanto, sumitsar
ms.date
11/04/2026
ms.service
sql
ms.subservice
connectivity
ms.topic
get-started
ms.custom
ignite-2025
ai-usage
ai-assisted
Microsoft Python Driver for SQL Server - mssql-python
mssql-python is Microsoft's Python driver for SQL Server, Azure SQL Database, Azure SQL Managed Instance, and SQL database in Microsoft Fabric. It uses Direct Database Connectivity (DDBC), so you can connect without installing an external driver manager. The driver supports Python 3.10 or later and complies with the Python Database API Specification 2.0 while adding Python-friendly improvements for day-to-day development.
This sample connects to Azure SQL with managed identity and Tabular Data Stream (TDS) 8.0 encryption. It reads connection settings from environment variables and sets separate login and query timeouts. Each retry calls connect() again instead of reusing a failed connection object. Context managers release the connection and cursor after each attempt.
Use this helper only for idempotent read queries that are safe to repeat. Don't use it to replay individual writes or partially completed transactions.
The ConnectRetryCount and ConnectRetryInterval keywords in the connection string enable SQL Server idle connection resiliency: the driver transparently reconnects a dropped idle connection. That's distinct from the application-level retry in this sample, which retries a query that fails with a transient error such as a deadlock or query timeout. The two are complementary, so keep both.
The Azure error check matches the standard English error 40501 message even when the diagnostic omits the error number. It also checks ddbc_error for known numbers when present. Matching is best-effort: localized or differently formatted messages might not match. For more information, see Transient connection errors.
importloggingimportosimportreimporttimeimportmssql_pythonlogging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger=logging.getLogger("app")
TRANSIENT_DRIVER_ERRORS=frozenset({
"Timeout expired",
"Connection timeout expired",
"Client unable to establish connection",
"Communication link failure",
"Connection failure during transaction",
"Serialization failure",
"Statement completion unknown",
})
AZURE_THROTTLING_ERRORS=frozenset({
40197, 40501, 40540, 40613, 40680, 49918, 49919, 49920, 10928, 10929,
})
_ERROR_NUMBER_RE=re.compile(r"\b(?:Error|Msg)\s+(\d+)\b")
_AZURE_40501_MESSAGE="The service is currently busy. Retry the request after 10 seconds."defis_azure_throttling(error: BaseException) ->bool:
"""Best-effort detection of Azure SQL throttling in ProgrammingError text."""ifnotisinstance(error, mssql_python.ProgrammingError):
returnFalseddbc_text=getattr(error, "ddbc_error", "") or""return (
_AZURE_40501_MESSAGEinddbc_textorany(int(m) inAZURE_THROTTLING_ERRORSformin_ERROR_NUMBER_RE.findall(ddbc_text))
)
defquery_with_retry(
conn_str: str,
sql: str,
*params,
max_attempts: int=3,
login_timeout_s: int=5,
query_timeout_s: int=10,
) ->list:
"""Fetch an idempotent read query, reconnecting before each retry."""forattemptinrange(1, max_attempts+1):
try:
withmssql_python.connect(conn_str, timeout=login_timeout_s) asconn:
conn.timeout=query_timeout_swithconn.cursor() ascursor:
cursor.execute(sql, *params)
rows=cursor.fetchall()
logger.info("query succeeded on attempt %d/%d", attempt, max_attempts)
returnrowsexceptmssql_python.Errorasexc:
azure_throttling=is_azure_throttling(exc)
transient= (
isinstance(exc, mssql_python.OperationalError)
andexc.driver_errorinTRANSIENT_DRIVER_ERRORS
)
ifnot (transientorazure_throttling) orattempt==max_attempts:
logger.error("query failed on attempt %d/%d: %s", attempt, max_attempts, exc.driver_error)
raisedelay= (10ifazure_throttlingelse1) * (2** (attempt-1))
logger.warning(
"query attempt %d/%d hit transient error %r; retrying in %ds",
attempt, max_attempts, exc.driver_error, delay,
)
time.sleep(delay)
raiseValueError("max_attempts must be at least 1")
defmain() ->None:
# Read configuration from the environment; never hard-code secrets.server=os.environ["SQL_SERVER"] # for example, <server>.database.windows.netdatabase=os.environ["SQL_DATABASE"] # for example, AdventureWorksclient_id=os.getenv("AZURE_CLIENT_ID") # set for a user-assigned managed identity# Authenticate with the workload's managed identity over TDS 8.0 encryption.# ConnectRetryCount/ConnectRetryInterval transparently reconnect a dropped# idle connection; they don't replay a failed query.conn_str= (
f"Server={server};"f"Database={database};""Authentication=ActiveDirectoryMsi;""Encrypt=strict;""ConnectRetryCount=3;""ConnectRetryInterval=10;"# Parallel dials to all resolved IPs; safe on single-IP targets."MultiSubnetFailover=Yes;"
)
ifclient_id:
conn_str+=f"UID={client_id};"query=""" SELECT TOP 10 p.BusinessEntityID, p.FirstName, p.LastName FROM Person.Person AS p ORDER BY p.BusinessEntityID; """try:
rows=query_with_retry(conn_str, query)
forbusiness_entity_id, first_name, last_nameinrows:
print(f"{business_entity_id}\t{first_name}\t{last_name}")
exceptmssql_python.Error:
logger.exception("query failed")
raiseif__name__=="__main__":
main()
Apache Arrow integration: Zero-copy result sets for fast data interchange with pandas, Polars, and DuckDB.
Async patterns: Use the driver with asyncio-based applications and FastAPI through ThreadPoolExecutor workarounds. See Async patterns for integration patterns.