在本快速入門中,您會用 uv 來管理 Python 腳本的專案相依性和環境,這些腳本會連線到您建立並載入範例資料的資料庫。 您可以使用 mssql-python Python 驅動程式連線到資料庫並執行基本操作,例如讀取和寫入資料。
在 Windows 電腦上,mssql-python 驅動程式不需要任何外部相依性。 驅動程式會透過單一 pip 安裝來安裝所需的所有內容,讓您可以將最新版本的驅動程式用於新腳本,而不會中斷您沒有時間升級和測試的其他腳本。
mssql-python 文件 | mssql-python 原始程式碼 | 套件 (PyPi) | uv
先決條件
蟒蛇3
如果您還沒有 Python,請從 python.org 安裝 Python 執行階段和 Python 套件索引 (PyPI) 套件管理員。
不想使用自己的環境? 使用 GitHub Codespaces 開啟為開發容器。
Visual Studio Code 使用下列擴充套件:
如果您還沒有
uv,請按照uv中的指示安裝https://docs.astral.sh/uv/getting-started/installation/。SQL Server、Azure SQL Database 或 Fabric 中的 SQL 資料庫上的資料庫,具有
AdventureWorks2025範例結構描述和有效的連接字串。安裝一次性作業系統特定先決條件。
建立 SQL 資料庫
此快速入門需使用 AdventureWorks2025 輕量級 架構,支援 Microsoft SQL Server、Fabric 中的 SQL 資料庫或 Azure 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 包含專案的中繼資料。 在您最喜歡的編輯器中打開該文件。
檢閱檔案的內容。 它應該類似於這個例子。 請注意 Python 的版本和相依性,
mssql-python使用>=來定義最低版本。 如果您偏好確切的版本,請將版本號碼之前的 變更>=為==。 然後,每個套件的解析版本會儲存在 uv.lock 中。 鎖定檔案可確保處理專案的開發人員使用一致的套件版本。 它也會確保在將套件分發給一般使用者時,使用完全相同的套件版本集。 您不應該編輯檔案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 test!")用這個代碼替換它。
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"小提示
此處使用的連接字串很大程度上取決於您要連線的 SQL 資料庫類型。 如果您要連線到 Azure SQL 資料庫 或 Fabric 中的 SQL 資料庫,請使用 [連接字串] 索引標籤中的 ODBC 連接字串。您可能需要根據您的案例調整驗證類型。 如需連接字串及其語法的詳細資訊,請參閱 連接字串語法參考。
使用 uv run 執行腳本
小提示
若要在 macOS 中使用 Microsoft Entra 驗證,您必須透過 Visual Studio Code 中的 Azure Repos 延伸模組登入,或透過 az login 執行。
在先前的終端機視窗中,或開啟至相同目錄的新終端機視窗中,執行下列命令。
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 │ └─────────────┴────────────────────────────────┴─────────────┘若要將指令碼部署到另一台電腦,請將資料夾以外的
.venv所有檔案複製到另一部電腦。 虛擬環境會在第一次執行時重新建立。
後續步驟
請造訪 mssql-python 驅動程式 GitHub 存放庫以取得更多範例,以提供想法或報告問題。