Connect Python to SQL Server Azure and run basic queries
Prerequisites
pyodbc
ODBC Driver 18 for SQL Server
1.install pyodbc
from command prompt run the below command, pyodbc will add into .venv
c:\project\database_agent\uv add pyodbc
validation
uv run python -c "import pyodbc; print(pyodbc.version)"
2. install ODBC Driver 18 for SQLServer
Download ODBC Driver for SQL Server - ODBC Driver for SQL Server | Microsoft Learn
python script to connect toSQL Azure and run basic queries
a). create python script sql_connect.py
import pyodbc
SERVER = "your-server-name.database.windows.net"
DATABASE = "your-database-name"
USERNAME = "your-username"
PASSWORD = "your-password"
conn_str = (
"DRIVER={ODBC Driver 18 for SQL Server};"
f"SERVER={SERVER};"
f"DATABASE={DATABASE};"
f"UID={USERNAME};"
f"PWD={PASSWORD};"
"Encrypt=yes;"
"TrustServerCertificate=no;"
"Connection Timeout=30;"
)
with pyodbc.connect(conn_str) as conn:
cursor = conn.cursor()
cursor.execute("SELECT @@VERSION")
print(cursor.fetchone()[0])
b) Run the command from Visual Code terminal
(database-agent) C:\project\database_agent> python sql_connect.py
It shows the result as below
(database-agent) C:\project\database_agent> python sql_connect.py
Microsoft SQL Azure (RTM) - 12.0.2000.8
Oct 2 2025 00:38:42
Copyright (C) 2025 Microsoft Corporation
No comments:
Post a Comment