快速入門:使用適用於 Python 的 mssql-python 驅動程式進行可重複的部署

在這個快速入門中,你會用uv來管理一個 Python 腳本的專案相依與環境,該腳本會連接到你建立並載入範例資料的資料庫。 你使用 mssql-python Python 驅動程式連接資料庫並執行基本操作,例如讀寫資料。

在 Windows 電腦上,mssql-python 驅動程式不需要任何外部相依性。 驅動程式會透過單一 pip 安裝來安裝所需的所有內容,讓您可以將最新版本的驅動程式用於新腳本,而不會中斷您沒有時間升級和測試的其他腳本。

MSSQL-Python 文件 | MSSQL-Python 原始碼 | 套件(PyPI) | uv

先決條件

  • Python 3.10 或更新版本。

  • 如果你還沒有 Python,建議安裝 Python 執行環境 和 Pip 套件管理器 ,從 python.org 安裝。

  • 不想使用自己的系統環境? 遵循容器與本地開發,建立可重現的開發容器或 GitHub Codespaces 環境。

  • Visual Studio Code 使用下列擴充套件:

  • Azure Command-Line 介面(CLI)用於 macOS 和 Linux 的無密碼認證。

  • 如果你還沒有安裝<該軟體>,請依照 安裝說明進行操作。

  • SQL Server、Azure SQL Database 或 Fabric 中的 SQL 資料庫上的資料庫,具有 AdventureWorks2025 範例結構描述和有效的連接字串。

安裝作業系統的先決條件

安裝一次性作業系統特定先決條件。 Windows 使用者可以跳過此步驟。 完整平台細節請參見 安裝 mssql-python。

apk add libtool krb5-libs krb5-dev libstdc++

建立 SQL 資料庫

在以下平台建立或連接 SQL 資料庫:

建立專案並執行程式碼

建立新專案

  1. 在開發目錄中開啟命令提示字元。 如果你沒有,請建立一個新的目錄,例如 python 或 scripts。 避免在 OneDrive 上放置資料夾,因為同步可能會干擾虛擬環境的管理。

  2. 建立新的專案 使用uv。

    uv init mssql-python-repeatable-qs
    cd mssql-python-repeatable-qs
    

新增相依項目

在相同的目錄中,安裝 mssql-python、 python-dotenv和 rich 套件。

uv add mssql-python python-dotenv rich

啟動 Visual Studio Code

在相同的目錄中,執行下列命令。

code .

更新 pyproject.toml

  1. 在您的編輯器中開啟 pyproject.toml 檔案。 這個檔案包含你專案的元資料。

  2. 檢閱檔案的內容。 它應該類似於這個例子。 請注意針對 mssql-python 的 Python 版本和相依性,並使用 >= 來定義最低版本。 如果您偏好確切的版本,請將版本號碼之前的 變更 >= 為 ==。 每個套件的解析版本會儲存在 uv.lock 中。 鎖定檔案確保開發者使用一致的套件版本。 它也會確保在將套件分發給一般使用者時,使用完全相同的套件版本集。 一併提交 pyproject.toml 和 uv.lock,檢視拉取請求中的鎖定檔變更,並在 CI 中執行經組織核准的相依性掃描器。 不要直接編輯 uv.lock 檔案。

    [project]
    name = "mssql-python-repeatable-qs"
    version = "0.1.0"
    description = "Add your description here"
    readme = "README.md"
    requires-python = ">=3.11"
    dependencies = [
        "mssql-python>=1.16.0",
        "python-dotenv>=1.1.1",
        "rich>=14.1.0",
    ]
    
  3. 更新 description 數值。

    description = "Connects to a SQL database using mssql-python"
    
  4. 儲存並關閉檔案。

更新 main.py

  1. 開啟名為 main.py的檔案。 它應該類似於這個例子。

    def main():
        print("Hello from mssql-python-repeatable-qs!")
    
    if __name__ == "__main__":
        main()
    
  2. 在檔案頂端,於包含 def main() 的那一行之前加入以下匯入內容。

    小提示

    如果 Visual Studio Code 在解析套件時遇到問題,您必須 更新解譯器才能使用虛擬環境。

    from os import getenv
    from dotenv import load_dotenv
    from mssql_python import connect, Connection, Cursor
    from rich.console import Console
    from rich.progress import Progress, SpinnerColumn, TextColumn
    from rich.table import Table
    from argparse import ArgumentParser
    from time import sleep
    
  3. 在匯入和def main()行之間,新增下列程式碼。

    def get_results(sleep_time: int = 0) -> None:
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            transient=True,
        ) as progress:
            task = progress.add_task(description="Connecting to SQL...")
    
            cursor = query_sql()
    
            # Simulate a slow connection for demo purposes
            sleep(sleep_time)
    
            progress.update(task, description="Formatting results...")
    
            table = Table(title="Orders by Customer")
            # https://rich.readthedocs.io/en/stable/appendix/colors.html
            table.add_column("Customer ID", style="bright_blue", justify="center")
            table.add_column("Company Name", style="bright_white", justify="left")
            table.add_column("Order Count", style="bold green", justify="right")
    
            records = cursor.fetchall()
            for r in records:
                table.add_row(f"{r.CustomerID}", f"{r.CompanyName}", f"{r.OrderCount}")
    
            if cursor:
                cursor.close()
    
            # Simulate a slow connection for demo purposes
            sleep(sleep_time)
    
            progress.stop()
    
            Console().print(table)
    
  4. 在匯入和 def get_results(sleep_time: int = 0) -> None:之間新增此程式碼。

    _connection = None
    
    def get_connection() -> Connection:
        global _connection
        if not _connection:
            load_dotenv()
            _connection = connect(getenv("SQL_CONNECTION_STRING"))  # type: ignore
        return _connection
    
    def query_sql() -> Cursor:
        SQL_QUERY = """
        SELECT TOP 5
            c.CustomerID,
            c.CompanyName,
            COUNT(soh.SalesOrderID) AS OrderCount
        FROM SalesLT.Customer AS c
        LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh
            ON c.CustomerID = soh.CustomerID
        GROUP BY
            c.CustomerID,
            c.CompanyName
        ORDER BY OrderCount DESC;
        """
    
        conn = get_connection()
        cursor = conn.cursor()
        cursor.execute(SQL_QUERY)
        return cursor
    
  5. 找到這個代碼。

    def main():
        print("Hello from mssql-python-repeatable-qs!")
    
  6. 用這個代碼替換它。

    def main() -> None:
        parser = ArgumentParser()
        parser.add_argument("--sleep-time", type=int, default=0,
                            help="Time to sleep in seconds to simulate slow connection")
        args = parser.parse_args()
    
        if args.sleep_time > 0:
            get_results(args.sleep_time)
        else:
            get_results()
    
        if _connection:
            _connection.close()
    
  7. 儲存並關閉 main.py。

儲存連接字串

  1. 開啟 .gitignore 檔案,並為 .env 檔案新增排除項目。 你的檔案應該與以下範例相似。

    # Python-generated files
    __pycache__/
    *.py[oc]
    build/
    dist/
    wheels/
    *.egg-info
    
    # Virtual environments
    .venv
    
    # Connection strings and secrets
    .env
    
  2. 儲存並關閉 .gitignore。

  3. 在目前目錄中,建立名為 的新檔案 .env。

  4. 在 .env 檔案中,新增名為 SQL_CONNECTION_STRING 的連接字串項目。 將佔位符替換成您的實際值。

    SQL_CONNECTION_STRING="Server=<server>;Database=<database>;Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryInteractive"
    

    Important

    保持本地化 .env ,且不使用原始碼控制。 對於 CI 和已部署的環境,請從平台的祕密儲存區中注入連線字串或其組成祕密,而不要在不同機器之間複製 .env。

    連接字串 取決於你連接的 SQL 資料庫類型。 對於 Azure SQL Database 或 Fabric 中的 SQL 資料庫,請使用 連接字串s 標籤中的 ODBC 連接字串,並根據你的情境調整認證類型。 欲了解更多關於 連接字串 語法的資訊,請參閱 mssql-python 的 Connection strings。

    小提示

    在 macOS 上,兩者都ActiveDirectoryInteractiveActiveDirectoryDefault適用於 Microsoft Entra 認證。 ActiveDirectoryInteractive 每次執行腳本時都會提示你登入。 為避免重複出現登入提示,請使用 Azure CLIaz login 命令登入一次,並使用 ActiveDirectoryDefault。 ActiveDirectoryDefault 重複使用快取的憑證。

使用 uv run 執行腳本

  1. 在先前的終端機視窗中,或開啟至相同目錄的新終端機視窗中,執行下列命令。

    uv run main.py
    
  2. 再次執行腳本並加入延遲,這樣你就能看到兩個狀態更新。

    uv run main.py --sleep-time 5
    

    以下是指令碼完成時的預期輸出。

                             Orders by Customer
    ┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
    ┃ Customer ID ┃ Company Name                   ┃ Order Count ┃
    ┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
    │    29485    │ Professional Sales and Service │           1 │
    │    29531    │ Remarkable Bike Store          │           1 │
    │    29546    │ Bulk Discount Store            │           1 │
    │    29568    │ Coalition Bike Company         │           1 │
    │    29584    │ Futuristic Bikes               │           1 │
    └─────────────┴────────────────────────────────┴─────────────┘
    
  3. 若要將腳本部署到另一台機器,請複製專案檔案,包括 pyproject.toml 和 uv.lock,但不要 .venv 複製資料夾或任何本地 .env 檔案。 首次執行時重建虛擬環境,並透過目標環境提供機密。