接続文字列をプログラム的に構築する

多くのアプリケーションは接続文字列を静的な設定値として保存するのではなく、動的に構築する必要があります。 あなたの展開に合ったアプローチを選択してください:

  • 環境変数:コンテナ、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 を使用する

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)

ヒント

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 Key Vault の統合

本番環境でのデプロイでは、接続資格情報を設定ファイルや環境変数ではなくAzure Key Vaultに保存してください。 Key Vaultは、集中管理の秘密管理、アクセス監査、自動ローテーションを提供します。 必要なパッケージは pip install azure-keyvault-secrets azure-identityを実行してインストールしてください。 詳細なウォークスルーは、PythonのQuickstart: Azure Key Vault secret client library をご覧ください

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")