許多應用程式需要動態建立連接字串,而非將其儲存為靜態配置值。 選擇符合你部署方式的方法:
- 環境變數:最適合容器、CI/CD 和 12 因子應用程式。 簡單且廣受支持。
- JSON/YAML 設定檔:最適合需要結構化配置的多個環境(開發、暫定、生產)應用程式。
- Azure Key Vault:最適合用於必須集中管理及稽核祕密的生產環境部署。
- 建構類別:最適合需要從使用者輸入中建構連接字串並自動轉義的函式庫或框架。
基本弦的構造
使用 f 字串
F 字串是快速腳本和原型常見的使用方法。 當值來自使用者輸入時,請避免此模式,因為惡意值(如) mydb;Server=evil.com 可能會改變連線目標:
import mssql_python
server = "<server>.database.windows.net"
database = "<database>"
connection_string = f"Server={server};Database={database};Authentication=ActiveDirectoryDefault;Encrypt=yes;"
conn = mssql_python.connect(connection_string)
使用聯結
此 join 方法將鍵值對分離成字典式函式呼叫,比長 f 字串更易閱讀與維護。 它也會自動過濾掉 None 值,因此你可以傳入選用參數,而不需要額外的條件邏輯:
def build_connection_string(**kwargs) -> str:
"""Build connection string from keyword arguments."""
return ";".join(f"{key}={value}" for key, value in kwargs.items() if value is not None)
conn_str = build_connection_string(
Server="<server>.database.windows.net",
Database="<database>",
Authentication="ActiveDirectoryDefault",
Encrypt="yes"
)
conn = mssql_python.connect(conn_str)
連接字串產生器類別
建構者類別提供流暢 API,並具備自動逸出功能。 此方法適用於函式庫或多租戶應用,當連線參數來自不同來源時:
import mssql_python
class ConnectionStringBuilder:
"""Builder for SQL Server connection strings."""
def __init__(self):
self._params = {}
def server(self, value: str) -> "ConnectionStringBuilder":
self._params["Server"] = value
return self
def database(self, value: str) -> "ConnectionStringBuilder":
self._params["Database"] = value
return self
def trusted_connection(self) -> "ConnectionStringBuilder":
self._params["Trusted_Connection"] = "yes"
return self
def sql_auth(self, username: str, password: str) -> "ConnectionStringBuilder":
self._params["UID"] = username
self._params["PWD"] = password
return self
def entra_default(self) -> "ConnectionStringBuilder":
self._params["Authentication"] = "ActiveDirectoryDefault"
return self
def entra_msi(self, client_id: str = None) -> "ConnectionStringBuilder":
self._params["Authentication"] = "ActiveDirectoryMSI"
if client_id:
self._params["UID"] = client_id
return self
def encrypt(self, value: bool = True) -> "ConnectionStringBuilder":
self._params["Encrypt"] = "yes" if value else "no"
return self
def trust_server_certificate(self, value: bool = True) -> "ConnectionStringBuilder":
self._params["TrustServerCertificate"] = "yes" if value else "no"
return self
def connect_timeout(self, seconds: int) -> "ConnectionStringBuilder":
self._timeout = seconds
return self
def build(self) -> str:
"""Build the connection string."""
return ";".join(f"{k}={v}" for k, v in self._params.items())
def connect(self) -> mssql_python.Connection:
"""Build and connect."""
return mssql_python.connect(self.build(), timeout=getattr(self, '_timeout', 0))
# Usage examples
# Microsoft Entra authentication (recommended)
conn = (ConnectionStringBuilder()
.server("<server>.database.windows.net")
.database("<database>")
.entra_default()
.encrypt()
.connect())
# Azure with managed identity
conn = (ConnectionStringBuilder()
.server("<server>.database.windows.net")
.database("<database>")
.entra_msi()
.encrypt()
.connect())
基於環境的配置
來自環境變數
從環境變數讀取連線參數可以避免憑證進入原始碼,並跨區域開發、容器及 CI/CD 管線運作。 該函式會根據設定的變數檢查應使用的驗證方法:
import os
import mssql_python
def get_connection_from_env() -> mssql_python.Connection:
"""Build connection from environment variables."""
server = os.environ.get("SQL_SERVER")
database = os.environ.get("SQL_DATABASE")
if not server or not database:
raise ValueError("SQL_SERVER and SQL_DATABASE environment variables required")
# Check for authentication method
if os.environ.get("SQL_USE_MSI", "").lower() == "true":
# Azure Managed Identity
conn_str = f"Server={server};Database={database};Authentication=ActiveDirectoryMSI;Encrypt=yes;"
elif os.environ.get("SQL_TRUSTED_CONNECTION", "").lower() == "true":
# Windows authentication
conn_str = f"Server={server};Database={database};Trusted_Connection=yes;Encrypt=yes;"
else:
# SQL authentication
username = os.environ.get("SQL_USERNAME")
password = os.environ.get("SQL_PASSWORD")
if not username or not password:
raise ValueError("SQL_USERNAME and SQL_PASSWORD required for SQL authentication")
conn_str = f"Server={server};Database={database};UID={username};PWD={password};Encrypt=yes;"
return mssql_python.connect(conn_str)
# Usage
conn = get_connection_from_env()
使用 python-dotenv
這個 python-dotenv 套件會將 .env 檔案中的鍵值對載入環境變數,讓你的程式碼在本地開發和生產環境中都能以相同方式讀取憑證。
.env 檔案不納入版本控制(將其加入 .gitignore),而在部署環境中,則透過平台的祕密儲存區注入相同的變數。
安裝時用 pip install python-dotenv.
在你的專案根目錄建立 .env 一個包含連接參數的檔案:
# .env - add this file to .gitignore
SQL_SERVER=<server>.database.windows.net
SQL_DATABASE=<database>
SQL_USE_MSI=true
然後載入並使用這些數值到腳本中:
from dotenv import load_dotenv
import os
import mssql_python
# Load .env file into os.environ (no-op if the file doesn't exist)
load_dotenv()
server = os.getenv("SQL_SERVER")
database = os.getenv("SQL_DATABASE")
if not server or not database:
raise ValueError("SQL_SERVER and SQL_DATABASE must be set in .env or as environment variables")
use_msi = os.getenv("SQL_USE_MSI", "false").lower() == "true"
if use_msi:
conn_str = f"Server={server};Database={database};Authentication=ActiveDirectoryMSI;Encrypt=yes;"
else:
conn_str = f"Server={server};Database={database};Authentication=ActiveDirectoryDefault;Encrypt=yes;"
conn = mssql_python.connect(conn_str)
Tip
load_dotenv() 不會覆蓋環境中已設定的變數。 在生產環境中,透過你的平台設定相同的變數名稱(例如 App Service 應用程式設定或容器環境變數),然後完全跳過檔案 .env 。
以檔案為基礎的設定
來自 JSON 設定
JSON 設定檔讓你能在同一個地方為多個環境(開發、暫定、生產)定義連線設定。 函式會讀取檔案、選取目標環境,並從結構化設定中建立連線字串:
import json
import io
import mssql_python
def load_connection_from_json(config_file, environment: str = "development") -> str:
"""Load connection settings from a JSON config file or file-like object."""
config = json.load(config_file)
env_config = config.get(environment, {})
db_config = env_config.get("database", {})
params = {
"Server": db_config.get("server"),
"Database": db_config.get("database"),
"Encrypt": "yes" if db_config.get("encrypt", True) else "no",
}
auth_type = db_config.get("authentication", "sql")
if auth_type == "msi":
params["Authentication"] = "ActiveDirectoryMSI"
elif auth_type == "default":
params["Authentication"] = "ActiveDirectoryDefault"
elif auth_type == "windows":
params["Trusted_Connection"] = "yes"
else:
params["UID"] = db_config.get("username")
params["PWD"] = db_config.get("password")
return ";".join(f"{k}={v}" for k, v in params.items() if v)
# Example: load from an inline JSON config (in production, use open("config.json"))
sample_config = json.dumps({
"development": {
"database": {
"server": "localhost",
"database": "devdb",
"authentication": "windows",
"encrypt": False
}
},
"production": {
"database": {
"server": "prod.database.windows.net",
"database": "proddb",
"authentication": "msi",
"encrypt": True
}
}
})
conn_str = load_connection_from_json(io.StringIO(sample_config), "production")
print(f"Connection string: {conn_str}")
來自 YAML 設定檔
YAML 設定檔是 JSON 的可讀替代方案。 它們常用於 Python 專案和 Kubernetes 部署。 此方法從結構化 YAML 檔案讀取連線設定,並根據設定中定義的認證類型建立 連接字串。
執行 pip install pyyaml 來安裝套件。
在您的專案中建立 database.yml 檔案:
database:
server: <server>.database.windows.net
name: <database>
authentication: msi
encrypt: true
然後載入並使用腳本中的設定:
import yaml
import mssql_python
def load_from_yaml(config_path: str) -> mssql_python.Connection:
"""Load connection from YAML config."""
with open(config_path) as f:
config = yaml.safe_load(f)
db = config["database"]
parts = [
f"Server={db['server']}",
f"Database={db['name']}",
]
if db.get("trusted_connection"):
parts.append("Trusted_Connection=yes")
elif db.get("authentication") == "msi":
parts.append("Authentication=ActiveDirectoryMSI")
else:
parts.append(f"UID={db['username']}")
parts.append(f"PWD={db['password']}")
if db.get("encrypt", True):
parts.append("Encrypt=yes")
if db.get("trust_server_certificate"):
parts.append("TrustServerCertificate=yes")
return mssql_python.connect(";".join(parts))
conn = load_from_yaml("database.yml")
Azure 金鑰保存庫整合
對於生產部署,將連線憑證儲存在 Azure Key Vault,而非設定檔或環境變數。 金鑰保存庫 提供集中式的秘密管理、存取稽核及自動輪替功能。 透過執行 pip install azure-keyvault-secrets azure-identity. 來安裝所需的套件。 完整攻略請參考 Quickstart: Azure Key Vault secret client library for Python。
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
import mssql_python
def get_connection_from_keyvault(vault_url: str) -> mssql_python.Connection:
"""Build connection using secrets from Azure Key Vault."""
credential = DefaultAzureCredential()
client = SecretClient(vault_url=vault_url, credential=credential)
server = client.get_secret("sql-server").value
database = client.get_secret("sql-database").value
username = client.get_secret("sql-username").value
password = client.get_secret("sql-password").value
conn_str = f"Server={server};Database={database};UID={username};PWD={password};Encrypt=yes;"
return mssql_python.connect(conn_str)
vault_url = os.environ.get("AZURE_KEY_VAULT_URL")
if vault_url:
conn = get_connection_from_keyvault(vault_url)
處理特殊字元
逃逸分號與大括號
你需要跳脫包含特殊字元的 連接字串 值。 將該值括在大括號 {} 中,並將內部任何右大括號 } 寫成兩個:
def escape_value(value: str) -> str:
"""Escape special characters in connection string values."""
if ";" in value or "{" in value or "}" in value:
# Wrap in braces and escape internal braces
value = value.replace("}", "}}")
return "{" + value + "}"
return value
# Password with semicolon
password = "my;complex;password"
escaped_password = escape_value(password) # {my;complex;password}
conn_str = f"Server=<server>;Database=<database>;UID=<login>;PWD={escaped_password};"
具備自動跳脫功能的建構器
這個建構類別會自動包裝每個值,讓呼叫者不必記住逃脫規則。 當連線參數來自外部輸入,如使用者表單、設定 API 或秘密儲存庫,其中值可能包含分號或大括號時,請使用此方法:
class SafeConnectionStringBuilder:
"""Connection string builder with automatic escaping."""
SPECIAL_CHARS = {";", "{", "}"}
def __init__(self):
self._params = {}
def _escape(self, value: str) -> str:
if any(c in value for c in self.SPECIAL_CHARS):
value = value.replace("}", "}}")
return "{" + value + "}"
return value
def set(self, key: str, value: str) -> "SafeConnectionStringBuilder":
self._params[key] = self._escape(value)
return self
def build(self) -> str:
return ";".join(f"{k}={v}" for k, v in self._params.items())
# Safely handles special characters
builder = SafeConnectionStringBuilder()
builder.set("Server", "<server>.database.windows.net")
builder.set("Database", "<database>")
builder.set("PWD", "pass;word{with}special") # Automatically escaped
conn_str = builder.build()
Validation
在應用程式中使用動態建立的連接字串之前,請先確認它確實可以成功連線。 此輔助函式嘗試輕量級查詢並回傳布林值結果:
import mssql_python
def validate_connection_string(conn_str: str) -> bool:
"""Validate a connection string by attempting to connect."""
try:
conn = mssql_python.connect(conn_str)
cursor = conn.cursor()
cursor.execute("SELECT 1")
cursor.fetchone()
conn.close()
return True
except mssql_python.Error as e:
print(f"Connection failed: {e}")
return False
# Test before using
conn_str = "Server=<server>.database.windows.net;Database=<database>;Authentication=ActiveDirectoryDefault;Encrypt=yes;"
if validate_connection_string(conn_str):
print("Connection string is valid")