Wednesday, January 07, 2026

Connect Python to SQL Server Azure and run basic queries

 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




Setup local dev environment 2 (UV, python virtual environment, python in Visual Code)

Setup local dev environment 2 (UV, python virtual environment, python in Visual Code)


UV

We use uv instead of pip for package management because uv is faster, safer, and manages dependencies per project automatically.

UV creates virtual environments, installs packages, locks dependencies, and runs Python — automatically and safely per project.

uv replaces pip + venv + pip-tools with a single, much faster tool.

Key idea:

You work in a project folder, and uv makes sure the right Python + the right packages + the right environment are always used — even without activating a virtual environment.

1. download and install UV for window 

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Reference Installation | uv

2. create folder prepare for the project

C:\project\database_agent


3) Inside c:\project\database_agent folder, run the below

UV init

it Creates a modern Python project folder structure as below inside c:\project\database_agent folder:

database_agent/ ├── .venv/ ├── pyproject.toml ├── README.md └── .gitignore

4) Creates the project’s Python virtual environment (.venv) and prepares it to be used by uv.
uv init

database_agent/ ├── .venv/ ├── pyproject.toml ├── README.md └── .gitignore
└── .venv

5) Open Visual code, file->open folder c:\project\database_agent

6) in Visual Code- >extention - > install python and pylance

7) Setup python interprate
visual code -> view- > palatte -> python: select interpreter

8) select interpreter from environment create by UV just now;
python 3.13.11 is the python version i create with UV
python 3.13.11 (database agent) .\venv\scripts\python.exe

9) Validate we use the right virtual environment
Visual code-> Terminal -> New terminal
If the following is shown, the environment is set up correctly and the virtual environment we created is being used.

(database-agent) C:\project\database_agent>

Deploy Azure SQL or SQL Server on Azure VM

 Deploy Azure SQL or SQL Server on Azure VM


from Azure database, select create Database - > SQL database (free offer)

if server not exists yet, create new server
















































back to resource group, that is one sql database service and window service create under the resource group



get SQL database connection 
























download and install ssms

test connection connect to SQL Azure 














Create Azure account, resource groups, access mode

 

Create Azure account, resource groups, access mode

1.create subscription

2, Create Azure account

Create Your Azure Free Account Or Pay As You Go | Microsoft Azure

















Try Azure for free to create account

3. Create resource group inside Azure portal







































4. click on resource name

















5 . click on access control (IAM) to explore access mode; 

Setup local dev environment (Python, IDE, Git)

 

Setup local dev environment (Python, IDE, Git)

1. download and install Visual Code

Download Visual Studio Code - Mac, Linux, Windows


2. download GIT

Git

from command prompt - Run the below

C:\>git --version

git version 2.51.1.windows.1


3. Install and install Python

Python Releases for Windows | Python.org

🗓 30-Day High-Level Plan Build an AI-enabled Cloud Database Agent in 30 days


📅 Week 1 – Cloud, Database & Automation Foundation

DayFocus AreaHigh-Level Taskstatus
1EnvironmentSetup local dev environment (Python, IDE, Git)done 6/Jan
2Azure BasicsCreate Azure account, resource groups, access modeldone 6/Jan
3DatabaseDeploy Azure SQL or SQL Server on Azure VMdone 6/Jan
4ConnectivityConnect Python to SQL Server and run basic queriesdone 7/Jan
5AutomationAutomate core DB operations (create, query, maintain)
6Azure AutomationAutomate DB lifecycle using Azure CLI / PowerShell
7StabilizationReview scripts, logging, error handling

📅 Week 2 – GenAI + Prompt → SQL + RAG

DayFocus AreaHigh-Level Task
8LLM SetupEnable Azure OpenAI and call LLM from Python
9Prompt DesignDesign prompts for natural language → SQL
10SQL CopilotBuild basic SQL Copilot (NL → SQL → Execute)
11EmbeddingsCreate embeddings for schema & runbooks
12RAGImplement retrieval-augmented SQL generation
13ReasoningEnable multi-step reasoning for complex queries
14OptimizationRefine prompts, add execution logging

📅 Week 3 – AI Agent + Automation

DayFocus AreaHigh-Level Task
15Agent CoreInitialize AI Agent framework and control loop
16ToolingRegister SQL, PowerShell, Azure CLI as Agent tools
17ProvisioningAgent-driven database provisioning
18DR / BackupAgent-driven backup and restore operations
19Incident OpsAgent-assisted incident diagnosis and recommendations
20End-to-EndChain reasoning → action → feedback
21GovernanceAdd guardrails, approval flow, safety controls

📅 Week 4 – UI, Demo & Presentation

DayFocus AreaHigh-Level Task
22UIBuild minimal UI for interacting with the Agent
23IntegrationConnect UI to Agent workflows
24ObservabilityAdd logging, transparency, execution feedback
25SecurityApply role separation and safe-execution rules
26KnowledgeEnhance Agent with runbooks and SOP knowledge
27ScenariosPrepare real-world demo scenarios
28DemoRecord demo video and walkthrough
29DocumentationCreate architecture and usage documentation
30FinalizationPolish solution and prepare interview narratives