Databases: Azure SQL basics, connecting from Python
Lesson opener
In one line: Azure SQL is SQL Server as a resource; connect with a parsed connection string and parameterized queries — never string-built SQL.
Why it matters: A Noida app that concatenates city names into SQL is an injection bug; a database left at a provisioned tier is a weekend bill.
Before this lesson: Storage.
Before you start
What you will learn
By the end of this lesson you will be able to:
- Parse an ADO.NET-style Azure SQL connection string into server, database, and user.
- Connect the same way from Python using a local SQLite stand-in (no live server).
- Run a parameterized
SELECTso values never enter the SQL text. - Refuse admin accounts in application code.
- Stop the database meter by pausing, scaling down, or deleting the resource.
- Walk the portal create path for Azure SQL in text.
What Azure SQL is
Azure SQL Database is Microsoft SQL Server offered as a managed resource: you pick a server name, a database name, a tier, and a region. The engine understands T-SQL. The resource is what bills.
This course does not install a cloud database. The method is: parse the official connection-string keys, then use parameters for values. The runnable blocks use SQLite so scripts/test_course_code.py can run without a server.
WHY The connection string is a secret. SQL text with interpolated values is a bug.
WHEN Any time an app or notebook talks to Azure SQL.
Cost. Provisioned Azure SQL can bill while the database exists, not only while you query. Serverless tiers can pause after idle; provisioned tiers do not. Delete the database (and the logical server if unused) or the resource group. Closing Python does not pause Azure SQL.
Portal click-path (text only)
- Resource group → Create → SQL Database (Azure SQL).
- Basics: subscription, group, database name, Create new server (name, admin, region). Prefer Entra auth when the org requires it; if you use SQL auth, store the password in a secret store, not in the notebook.
- Compute + storage: start at the smallest tier that matches the offer. Read the estimated cost on the blade.
- Networking: allow your client IP only for a lab. Do not tick "allow Azure services" unless you know why.
- Tags, then Create.
- Connection strings blade → copy ADO.NET or ODBC. Those keys are what Python drivers expect.
- Teardown: delete the database, then the logical server, or delete the group.
Demo 1 — Parse a connection string
Official ADO.NET keys include Server, Database, User ID / Uid, Password / Pwd.
def parse_conn(conn: str) -> dict:
parts = {}
for item in conn.split(";"):
if "=" not in item:
continue
key, value = item.split("=", 1)
parts[key.strip().lower()] = value.strip()
server = parts.get("server") or parts.get("data source")
database = parts.get("database") or parts.get("initial catalog")
user = parts.get("uid") or parts.get("user id")
if not server or not database:
raise ValueError("server and database required")
return {"server": server, "database": database, "user": user or ""}
raw = (
"Server=tcp:sql-churn-lab.database.windows.net,1433;"
"Database=churn;"
"Uid=labuser;"
"Pwd=not-a-real-password;"
"Encrypt=yes;"
)
info = parse_conn(raw)
print(info["database"])
print("windows.net" in info["server"])
print(info["user"])
assert info["database"] == "churn"Expected output:
churn
True
labuserDemo 2 — Parameterized query (SQLite stand-in)
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (city TEXT, amount REAL)")
con.executemany(
"INSERT INTO orders VALUES (?, ?)",
[("Bengaluru", 120.0), ("Pune", 80.0), ("Bengaluru", 40.0)],
)
def total_for(city: str) -> float:
cur = con.execute("SELECT SUM(amount) FROM orders WHERE city = ?", (city,))
value = cur.fetchone()[0]
return float(value or 0.0)
print(total_for("Bengaluru"))
print(total_for("Mumbai"))
assert total_for("Bengaluru") == 160.0
con.close()Expected output:
160.0
0.0A driver for Azure SQL uses the same idea: ? or %s placeholders, values in a tuple — never f"WHERE city = '{city}'".
Demo 3 — Refuse admin in app settings
def may_use_login(username: str, role: str) -> str:
if role in {"admin", "server-admin"}:
return "refuse-admin-in-app"
if not username:
return "refuse-empty-user"
return "ok-app-user"
print(may_use_login("sqladmin", "server-admin"))
print(may_use_login("app_readonly", "reader"))
assert may_use_login("", "reader") == "refuse-empty-user"Expected output:
refuse-admin-in-app
ok-app-userGuided practice: catch string-built SQL
def looks_interpolated(sql: str) -> bool:
return "'" in sql and "WHERE" in sql.upper()
print(looks_interpolated("SELECT * FROM orders WHERE city = ?"))
print(looks_interpolated("SELECT * FROM orders WHERE city = 'Pune'"))
assert looks_interpolated("SELECT * FROM orders WHERE city = 'Pune'")Expected output:
False
TrueIndependent practice: sum with a parameter
Deliverable: insert three rows, print the count of rows for Pune.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE tickets (city TEXT)")
con.executemany("INSERT INTO tickets VALUES (?)", [("Pune",), ("Pune",), ("Jaipur",)])
n = con.execute("SELECT COUNT(*) FROM tickets WHERE city = ?", ("Pune",)).fetchone()[0]
print(n)
assert n == 2
con.close()Expected output:
2Common mistake
The deliberate mistake
Symptom: the notebook works from home and fails from the office, or the password is in git.
Diagnosis: firewall allows only one IP, or the connection string was pasted into a cell.
Correction: store secrets in environment variables or a key vault; add the office IP or a private endpoint.
Prevention: print
parse_connkeys (never the password) in logs. Delete the database when the lab ends.
Snapshot — checked September 2026
- Azure SQL Database connection strings and the
*.database.windows.nethost are documented under Azure SQL connectivity. ODBC Driver 18 is a current Microsoft driver name — confirm the driver you actually install. - Serverless auto-pause and provisioned billing rules change by tier. Read the create-blade estimate; do not assume pause.
- Free-account Azure SQL SKUs and GB amounts sit on Microsoft's free-services list and are time-boxed. They do not belong in the quiz.
Where this connects
What you can now do:
- Parse a connection string without printing the password.
- Query with parameters.
- Refuse admin logins inside app config.
Next lesson: Pipelines. Copy plus transform — still no live factory required.