mssql-python 驅動程式在連接 SQL Server、Azure SQL Database、Azure SQL 受控執行個體 及 Microsoft Fabric 中的 SQL 資料庫時,支援以下 連接字串 關鍵字。
連接字串語法
連接字串使用分號分隔的鍵值對:
keyword1=value1;keyword2=value2;...
包含特殊字元(分號、等號或大括號)的包裹值:
PWD={my;complex=password}
若要在值中包含字面的閉括括號,請使用兩個閉括括號(}}):
PWD={password}}with}}brace}
基本連接範例
以下範例說明如何使用不同的認證方法進行連線。 對於生產應用程式,盡可能使用 Microsoft Entra 認證。 它會從你的程式碼和連線字串中移除密碼。
SQL Server 搭配 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 Server 實例進行本地開發時使用 SQL 認證。 憑證嵌入在 連接字串 中,因此請將它們保留在環境變數或.env檔案中,而非原始碼中:
conn = mssql_python.connect(
"Server=<server>;"
"Database=<database>;"
"UID=<login>;"
"PWD=<password>;"
"Encrypt=yes;"
)
Azure SQL with Microsoft Entra authentication
Azure SQL Database 的 連接字串 與 SQL Server 相同。
ActiveDirectoryDefault可在本地開發、容器及 Azure 託管環境間運作,無需修改程式碼:
conn = mssql_python.connect(
"Server=<server>.database.windows.net;"
"Database=<database>;"
"Authentication=ActiveDirectoryDefault;"
"Encrypt=yes;"
)
使用關鍵字參數
你可以以關鍵字參數傳遞連線參數,取代或附加 連接字串。 關鍵字參數避免了 連接字串 組合時的陷阱。 帶有特殊字元如 @、 ;、 {或 } 在傳遞為關鍵字參數時不需要大括號的密碼:
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 實例與資料庫。
| Keyword | 別名 | 預設值 | 描述 |
|---|---|---|---|
Server |
addr、address |
None | SQL Server 主機名稱、IP 位址或命名實例。 對於命名實例,請使用 server\instance。 For Azure SQL, use server.database.windows.net. 若要指定埠,請使用 server,port。 |
Database |
None | None | 資料庫名稱要連接。 |
Authentication
提供 SQL 認證的憑證,或指定 Microsoft Entra 認證模式。 關於無密碼選項,請參閱 Microsoft Entra 認證模式。
| Keyword | 別名 | 預設值 | 描述 |
|---|---|---|---|
UID |
uid |
None | 使用者名稱用於 SQL 認證。 |
PWD |
pwd |
None | SQL 驗證密碼。 |
Trusted_Connection |
trusted_connection |
no |
請使用 Windows 整合驗證。 將其設為 yes 以啟用。 |
Authentication |
authentication |
None | Microsoft Entra 認證模式。 請參閱 Microsoft Entra 驗證。 |
加密與安全性
所有連線預設都會使用 Encrypt=yes 。 對大多數應用來說,預設值就足夠了。 只在你的 SQL Server 實例支援 TDS 8.0 且需要 TLS 1.3 時使用strict。 僅用於 TrustServerCertificate=yes 具備自簽憑證的開發環境。
| Keyword | 別名 | 預設值 | 描述 |
|---|---|---|---|
Encrypt |
encrypt |
yes |
啟用 TLS 加密。 數值: yes, no, strict。 用於 strictTDS 8.0 搭配強制性的 TLS 1.3。 |
TrustServerCertificate |
trust_server_certificate、trustservercertificate |
no |
信任無需驗證的自簽伺服器憑證。 設定為 yes 僅用於開發。 |
HostnameInCertificate |
hostnameincertificate |
None | 伺服器 TLS 憑證中的預期主機名稱。 |
ServerCertificate |
servercertificate |
None | 通往包含受信任憑證授權中心的 PEM 檔案的路徑。 |
ServerSPN |
serverspn |
None | Kerberos 認證的伺服器服務主體名稱。 |
高可用性與容錯移轉
這些關鍵字適用於 Always On 可用性群組部署。 設定 ApplicationIntent=ReadOnly 為將讀取量大的工作負載(報告、分析)路由到次要副本,減輕主副本的負載。 設定 MultiSubnetFailover=yes 在你的可用群組跨越多個子網時。
| Keyword | 別名 | 預設值 | 描述 |
|---|---|---|---|
MultiSubnetFailover |
multisubnetfailover |
no |
啟用 Always On 可用性群組的多子網路故障轉移。 |
ApplicationIntent |
applicationintent |
ReadWrite |
宣告應用程式工作負載類型。 用於 ReadOnly 唯讀路由至次級副本。 |
ConnectRetryCount |
connectretrycount |
1 |
為了 空閒連線韌性而自動重新連線嘗試次數。 這是針對空閒連線中斷的驅動程式層級功能,而非應用程式 層級重試邏輯的替代方案。 |
ConnectRetryInterval |
connectretryinterval |
10 |
空閒連線韌性與重新連線嘗試之間的幾秒。 |
表現與網絡
預設值對大多數應用程式來說都是可行的。 大量資料傳輸可提升 PacketSize 至最高 32767。 如果連線跨越防火牆或負載平衡器,導致閒置的 TCP 會話中斷,請設定 KeepAlive 。
| Keyword | 別名 | 預設值 | 描述 |
|---|---|---|---|
PacketSize |
packet size、packetsize |
4096 |
網路封包大小(位元組)(512–32767)。 |
KeepAlive |
keepalive |
None | TCP 保持生命週期以秒計。 |
KeepAliveInterval |
keepaliveinterval |
None | TCP 保持活絡重試間隔以秒為單位。 |
IpAddressPreference |
ipaddresspreference |
None | IP 位址家族偏好: IPv4First, IPv6First, UsePlatformDefault, |
保留關鍵字
| Keyword | 描述 |
|---|---|
Driver |
保留供內部使用。 司機會自動管理這個數值。 |
APP |
已保留。 總是由駕駛者設定為。"MSSQL-Python" |
Microsoft Entra 認證模式
關鍵字 Authentication 支援以下數值。 選擇最適合你部署的模式:
| 價值 | 描述 | 何時使用 |
|---|---|---|
ActiveDirectoryDefault |
用於 DefaultAzureCredential Azure Identity SDK。 嘗試多種認證方法依序進行。 |
Local Development across Azure CLI, Azure PowerShell, and Azure Developer CLI. 對於生產環境,請使用特定模式(ActiveDirectoryMSI, ActiveDirectoryServicePrincipal),以避免緩慢的憑證鏈行走。 |
ActiveDirectoryInteractive |
基於瀏覽器的互動式登入。 在 Windows 上,則會原生委託給 ODBC 驅動程式。 | 本地開發與工具,使用者在瀏覽器中進行驗證。 |
ActiveDirectoryDeviceCode |
無頭環境的裝置程式碼流程。 顯示輸入 https://microsoft.com/devicelogin代碼。 |
SSH 會話、Docker 容器或其他沒有瀏覽器的環境。 |
ActiveDirectoryPassword |
Deprecated. 使用 Microsoft Entra ID 進行使用者名稱與密碼驗證。 需要 UID 和 PWD。 使用 ROPC 流程,但與多重因素驗證(MFA)不相容。 |
不推薦。 請改用 ActiveDirectoryMSI 或 ActiveDirectoryServicePrincipal。 |
ActiveDirectoryMSI |
Managed Service Identity for Azure-hosted applications. | Azure VMS、App Service, or Azure Functions where where managed identity is config. 不需要任何證件。 |
ActiveDirectoryServicePrincipal |
服務主體認證。 需要( UID 用戶端 ID)和 PWD (用戶端秘密)。 |
CI/CD 管線與使用註冊應用程式識別碼的背景服務。 |
ActiveDirectoryIntegrated |
Windows 整合認證與 Microsoft Entra ID(Kerberos)。 | 企業環境中已設定 Kerberos 的網域加入 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 容器。 驅動程式會顯示一個網址和一個代碼,在另一台裝置上輸入:
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
自動認可模式
預設情況下, autocommit 是 False,這需要明確 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-strings。 改用關鍵字參數或環境變數。 更多建構模式,包括 JSON/YAML 設定檔、Azure Key Vault 以及建構類別,請參見「程式化建構連接字串」。
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'