在本快速入門中,您會用 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。
建立 SQL 資料庫
在以下平台建立或連接 SQL 資料庫:
建立專案並執行程式碼
建立新專案
在開發目錄中開啟命令提示字元。 如果你沒有,請建立一個新的目錄,例如
python或scripts。 避免在 OneDrive 上放置資料夾,因為同步可能會干擾虛擬環境的管理。建立新的專案 使用
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
pyproject.toml 包含專案的中繼資料。 在您最喜歡的編輯器中打開該文件。
檢閱檔案的內容。 它應該類似於這個例子。 請注意針對
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>=0.10.0", "python-dotenv>=1.1.1", "rich>=14.1.0", ]更新描述以更具描述性。
description = "Connects to a SQL database using mssql-python"儲存並關閉檔案。
更新 main.py
開啟名為
main.py的檔案。 它應該類似於這個例子。def main(): print("Hello from mssql-python-repeatable-qs!") if __name__ == "__main__": main()在檔案頂端,於包含
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在匯入和
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)在匯入和
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找到這個代碼。
def main(): print("Hello from mssql-python-repeatable-qs!")用這個代碼替換它。
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()儲存並關閉
main.py。
儲存連接字串
開啟
.gitignore檔案,並為.env檔案新增排除項目。 您的檔案應該類似於此範例。 請務必儲存並在完成後將其關閉。# Python-generated files __pycache__/ *.py[oc] build/ dist/ wheels/ *.egg-info # Virtual environments .venv # Connection strings and secrets .env在目前目錄中,建立名為 的新檔案
.env。在
.env檔案中,新增名為SQL_CONNECTION_STRING的連接字串項目。 將此處的範例替換為您的實際連接字符串值。SQL_CONNECTION_STRING="Server=<server_name>;Database=<database_name>;Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryInteractive"Important
保持本地化
.env,且不使用原始碼控制。 對於 CI 和已部署的環境,請從平台的祕密儲存區中注入連線字串或其組成祕密,而不要在不同機器之間複製.env。小提示
此處使用的連接字串很大程度上取決於您要連線的 SQL 資料庫類型。 如果您要連線到 Azure SQL 資料庫 或 Fabric 中的 SQL 資料庫,請使用 [連接字串] 索引標籤中的 ODBC 連接字串。您可能需要根據您的案例調整驗證類型。 如需連接字串及其語法的詳細資訊,請參閱 連接字串語法參考。
使用 uv run 執行腳本
小提示
在 macOS 上,兩者都ActiveDirectoryInteractiveActiveDirectoryDefault適用於 Microsoft Entra 認證。
ActiveDirectoryInteractive 每次執行腳本時都會提示你登入。 為避免重複登入提示,請透過 Azure CLI 執行 az login,然後使用 ActiveDirectoryDefault,重複使用快取的憑證。
在先前的終端機視窗中,或開啟至相同目錄的新終端機視窗中,執行下列命令。
uv run main.py現在讓我們再次運行它,但慢一些,以便能夠看到兩個狀態更新。
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 │ └─────────────┴────────────────────────────────┴─────────────┘若要將腳本部署到另一台機器,請複製專案檔案,包括
pyproject.toml和uv.lock,但不要.venv複製資料夾或任何本地.env檔案。 首次執行時重建虛擬環境,並透過目標環境提供機密。
下一步
善用這些文章持續學習: