mssql-python 的连接字符串

mssql-python驱动在连接Microsoft Fabric SQL Server、Azure SQL 数据库、Azure SQL 托管实例和SQL数据库时支持以下连接字符串关键词。

连接字符串语法

连接字符串使用分号分隔的键值对:

keyword1=value1;keyword2=value2;...

包含特殊字符(分号、等号或大括号)的包裹值:

PWD={my;complex=password}

要在值中包含字面闭括括号,使用两个闭括括号(}}):

PWD={password}}with}}brace}

基本连接示例

以下示例展示了如何使用不同的认证方法进行连接。 对于生产应用,尽可能使用Microsoft Entra认证。 它会从你的代码和连接字符串中去除密码。

这个例子使用 ActiveDirectoryDefault了 ,它按顺序尝试多个凭证源(Azure CLI、环境变量、托管身份)。 密码不存储在代码中:

import mssql_python

conn = mssql_python.connect(
    "Server=<server>.database.windows.net;Database=<database>;Authentication=ActiveDirectoryDefault;Encrypt=yes;"
)

SQL Server 与 SQL 认证

仅在本地开发时使用SQL认证,针对你控制的SQL Server实例。 凭据嵌入在连接字符串中,因此应保留在环境变量或.env文件中,而非源代码中:

conn = mssql_python.connect(
    "Server=<server>;"
    "Database=<database>;"
    "UID=<login>;"
    "PWD=<password>;"
    "Encrypt=yes;"
)

Azure SQL with Microsoft Entra authentication

Azure SQL 数据库 的 连接字符串 和 SQL Server 是一样的。 ActiveDirectoryDefault可在本地开发、容器和 Azure 托管环境下运行,无需修改代码:

conn = mssql_python.connect(
    "Server=<server>.database.windows.net;"
    "Database=<database>;"
    "Authentication=ActiveDirectoryDefault;"
    "Encrypt=yes;"
)

使用关键词参数

你可以作为关键词参数传递连接参数,替代或附加连接字符串。 关键词参数避免了 连接字符串 assembly 中常见的陷阱。 带有特殊字符如 @;{} 在传递为关键词参数时无需大括号的密码:

conn = mssql_python.connect(
    server="<server>.database.windows.net",
    database="<database>",
    authentication="ActiveDirectoryDefault",
    encrypt="yes"
)

与 连接字符串 assembly 比较,后者@密码必须包含:

# Connection string requires escaping
conn = mssql_python.connect("Server=srv;UID=user;PWD={p@ss;word};")

# Keyword arguments - no escaping needed
conn = mssql_python.connect(server="srv", uid="user", pwd="p@ss;word")

驱动在规范化后将关键词参数合并到连接连接字符串中。 如果关键词参数匹配连接字符串中已有的参数,关键字变量优先,并覆盖连接字符串值:

# The keyword argument database="production" overrides Database=dev in the connection string
conn = mssql_python.connect(
    "Server=<server>.database.windows.net;Database=<database>;Encrypt=yes;",
    database="production",
    authentication="ActiveDirectoryDefault"
)
# Connects to "production", not "dev"

以下示例将一个 连接字符串 与关键字参数结合:

conn = mssql_python.connect(
    "Server=<server>.database.windows.net;Database=<database>;",
    authentication="ActiveDirectoryDefault",
    encrypt="yes"
)

连接字符串关键字

服务器与数据库

指定连接的目标SQL Server实例和数据库。

关键 字 别名 默认 描述
Server addraddress 没有 SQL Server 主机名、IP 地址或命名实例。 对于命名实例,使用 server\instance。 对于Azure SQL,使用 server.database.windows.net. 要指定端口,请使用 server,port
Database 没有 没有 要连接到的数据库名称。

Authentication

提供SQL认证凭证,或指定Microsoft Entra认证模式。 关于无密码选项,请参见 Microsoft Entra 认证模式

关键 字 别名 默认 描述
UID uid 没有 SQL认证用户名。
PWD pwd 没有 SQL认证密码。
Trusted_Connection trusted_connection no 使用Windows集成认证。 设置为 yes 以启用。
Authentication authentication 没有 Microsoft Entra 认证模式。 请参阅 Microsoft Entra 身份验证

加密和安全性

所有连接默认使用 Encrypt=yes 。 对于大多数应用,默认即可。 只有在你的 SQL Server 实例支持 TDS 8.0 并且需要 TLS 1.3 时才使用strict。 仅在使用自签名证书的开发环境中使用 TrustServerCertificate=yes

关键 字 别名 默认 描述
Encrypt encrypt yes 启用 TLS 加密。 值:yes、、nostrict. 用于strictTDS 8.0,强制使用TLS 1.3。
TrustServerCertificate trust_server_certificatetrustservercertificate no 信任无需验证的自签名服务器证书。 设置为 yes 仅供开发使用。
HostnameInCertificate hostnameincertificate 没有 服务器TLS证书中的预期主机名。
ServerCertificate servercertificate 没有 路径指向包含受信任证书颁发机构的PEM文件。
ServerSPN serverspn 没有 Kerberos 认证的服务器服务主体名称

高可用性和故障转移

这些关键词适用于Always On可用性组部署。 设置为 ApplicationIntent=ReadOnly 将大量读取工作负载(报告、分析)路由到二级副本,从而减轻主副本的负载。 当你的可用性组跨越多个子网时设置 MultiSubnetFailover=yes

关键 字 别名 默认 描述
MultiSubnetFailover multisubnetfailover no 为Always On可用性组启用多子网故障切换。
ApplicationIntent applicationintent ReadWrite 声明应用工作负载类型。 用于 ReadOnly 只读路由到二级副本。
ConnectRetryCount connectretrycount 1 空闲连接弹性自动重连尝试次数。 这是驱动程序层面用于中断空闲连接的功能,不能替代 应用级重试逻辑
ConnectRetryInterval connectretryinterval 10 空闲连接弹性与重新连接尝试之间的秒数。

性能与网络

默认设置适用于大多数应用。 批量数据传输可增加 PacketSize (最高32767)。 如果连接跨越防火墙或负载均衡器,导致空闲的TCP会话被丢弃,请配置 KeepAlive

关键 字 别名 默认 描述
PacketSize packet sizepacketsize 4096 网络数据包大小(字节数)(512–32767)。
KeepAlive keepalive 没有 TCP的保持生命间隔以秒计。
KeepAliveInterval keepaliveinterval 没有 TCP 保持生命重试间隔以几秒计。
IpAddressPreference ipaddresspreference 没有 IP地址家族偏好: IPv4FirstIPv6FirstUsePlatformDefault

保留关键字

关键 字 描述
Driver 仅供内部使用。 司机会自动管理这个数值。
APP 保留。 总是由司机设置为。"MSSQL-Python"

Microsoft Entra 认证模式

Authentication 关键词支持以下数值。 选择与你部署相匹配的模式:

价值 描述 何时使用
ActiveDirectoryDefault 来自 Azure Identity SDK 的用途DefaultAzureCredential。 尝试多种认证方法依次验证。 Local Development across Azure CLI, Azure PowerShell and Azure Developer CLI. 对于生产环境,使用特定模式(ActiveDirectoryMSIActiveDirectoryServicePrincipal)以避免慢速的凭证链行。
ActiveDirectoryInteractive 基于浏览器的交互式登录。 在 Windows 上,原生代理给 ODBC 驱动。 本地开发和工具,用户可以在浏览器中进行身份验证。
ActiveDirectoryDeviceCode 无头环境的设备代码流。 显示输入 https://microsoft.com/devicelogin代码。 SSH会话、Docker容器或其他没有浏览器的环境。
ActiveDirectoryPassword Deprecated. 使用Microsoft Entra ID进行用户名和密码认证。 需要 UIDPWD。 使用 ROPC流程,但与多重身份验证不兼容。 不建议这样做。 请改用 ActiveDirectoryMSIActiveDirectoryServicePrincipal
ActiveDirectoryMSI Managed Service Identity for Azure-hosted applications. Azure VMS、App Service, or Azure Functions where where based management identity. 不需要凭据。
ActiveDirectoryServicePrincipal 服务主体认证。 需要 UID (客户端ID)和 PWD (客户端秘密)。 使用注册应用身份的CI/CD流水线和后台服务。
ActiveDirectoryIntegrated Windows 集成认证与 Microsoft Entra ID(Kerberos)。 在企业环境中配置了Kerberos的Domain-join型Windows机器。

关于可复现的 Docker、开发容器和 CI 环境设置,请参见 容器与本地开发。 那篇文章集中管理 Python 运行时的选择,并展示了如何在共享环境中使用摘要置顶图像。

示例:DefaultAzureCredential

ActiveDirectoryDefault映射到 Azure 身份DefaultAzureCredential链。 它在本地开发时先尝试使用 Azure CLI 令牌,部署到 Azure 时再尝试管理身份:

conn = mssql_python.connect(
    "Server=<server>.database.windows.net;"
    "Database=<database>;"
    "Authentication=ActiveDirectoryDefault;"
    "Encrypt=yes;"
)

示例:设备代码流

在没有浏览器的环境中运行时,如SSH会话或Docker容器,使用设备代码流。 驱动程序会在独立设备上显示一个URL和一个代码,以便输入:

conn = mssql_python.connect(
    "Server=<server>.database.windows.net;"
    "Database=<database>;"
    "Authentication=ActiveDirectoryDeviceCode;"
    "Encrypt=yes;"
)
# Follow the prompt to authenticate at https://microsoft.com/devicelogin

示例:服务主体

服务主体认证使用注册的应用程序身份,包含客户端ID和秘密。 对于无需用户交互运行的CI/CD流水线和后台服务,请使用此方法:

conn = mssql_python.connect(
    "Server=<server>.database.windows.net;"
    "Database=<database>;"
    "Authentication=ActiveDirectoryServicePrincipal;"
    "UID=<client-id>;"
    "PWD=<client-secret>;"
    "Encrypt=yes;"
)

要注册应用并授予其数据库访问权限,请参见 Microsoft Entra 服务主体与 Azure SQL。 关于完整设置, mssql-python请参见 服务主体认证

连接超时

用参数 timeout 设置连接超时。 使用超时防止应用在服务器无法访问时无限期卡住:

# 30-second connection timeout
conn = mssql_python.connect(connection_string, timeout=30)

你也可以更改现有连接的超时:

conn.timeout = 60

自动提交模式

默认情况下, autocommitFalse,这需要显式 commit() 调用。 启用对不需要事务控制的DDL语句或只读查询的自动提交功能:

# Via parameter
conn = mssql_python.connect(connection_string, autocommit=True)

# Or after connection
conn.setautocommit(True)

连接属性

在建立连接前,通过以下方式 attrs_before设置 ODBC 连接属性:

import mssql_python

conn = mssql_python.connect(
    connection_string,
    attrs_before={
        mssql_python.SQL_ATTR_LOGIN_TIMEOUT: 30,
        mssql_python.SQL_ATTR_CONNECTION_TIMEOUT: 60,
    }
)

程序化 连接字符串 构建

为防止 连接字符串 注入,用户输入时不要使用字符串串接或 f-string。 用关键词参数或环境变量代替。 关于更多构建模式,包括 JSON/YAML 配置文件、Azure 密钥保管库 以及构建类,请参见“编程构建连接字符串”。

import os

conn = mssql_python.connect(
    server=os.environ["DB_SERVER"],
    database=os.environ["DB_NAME"],
    authentication=os.environ.get("DB_AUTH", "ActiveDirectoryDefault"),
    encrypt="yes"
)

连接字符串验证

驱动程序验证连接字符串,并对未知或拼写错误的关键词进行 ConnectionStringParseError 加注:

try:
    conn = mssql_python.connect("Servr=localhost;")  # Typo
except mssql_python.ConnectionStringParseError as e:
    print(f"Invalid connection string: {e}")
    # Output: Unknown keyword 'Servr'