Connecting to PostgreSQL from Python
This lesson explains psycopg connections, keyless authentication with Microsoft Entra tokens, parameterized queries, transactions and bulk loading.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the parts of a PostgreSQL connection.
- Explain how Entra tokens are used and refreshed.
- Explain why queries must use parameters.
- Describe COPY and executemany for bulk loads.
Drivers and connection strings
Azure Database for PostgreSQL speaks the standard PostgreSQL protocol, so any PostgreSQL driver works. The most widely used Python driver is psycopg (version 3, installed as psycopg[binary]); its predecessor psycopg2, the asynchronous driver asyncpg and object-relational mappers such as SQLAlchemy are also common. Microsoft's Azure SDK is used alongside the driver only to obtain authentication tokens and to manage servers, not to run queries.
A connection needs the host (SERVER.postgres.database.azure.com), port 5432 (or 6432 for PgBouncer), the database name, the user and a password or token, and TLS. Setting sslmode=require encrypts the connection; verify-full also checks the server certificate and host name. Connection details belong in environment variables or App Configuration, never in code.
Drivers and connections
Keyless connections with Microsoft Entra tokens
With Microsoft Entra authentication, the application requests an access token for the Azure Database for PostgreSQL scope and passes the token as the password. The user name is the name of the database role mapped to the identity: a user principal name for a person, or the name chosen when a managed identity was added as a database principal.
import os
import psycopg
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
def connect():
token = credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
return psycopg.connect(
host=os.environ["PGHOST"], dbname=os.environ["PGDATABASE"],
user=os.environ["PGUSER"], password=token, sslmode="require")
with connect() as conn:
print(conn.execute("SELECT current_user, version()").fetchone())Tokens are valid for about an hour, but they are checked only when a connection is opened: an established connection keeps working after its token expires. Code that opens new connections later, including connection pools, must obtain a fresh token each time, which is why the example fetches the token inside connect(). DefaultAzureCredential caches tokens and renews them before expiry, so calling it often is cheap. To let a managed identity connect, the Entra administrator creates a matching role in the database, for example with the pgaadauth_create_principal function, and grants it privileges.
Letting a managed identity connect
Parameterized queries and results
Values are always passed separately from the SQL text, as query parameters. psycopg uses %s placeholders (or named %(name)s placeholders) and sends the values to the server separately, so a value containing quotes or SQL keywords cannot change the statement. Building SQL by string formatting with user input is the classic SQL injection vulnerability.
from psycopg.rows import dict_row
with connect() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"SELECT id, title, updated_at FROM documents WHERE tenant_id = %s AND updated_at > %s "
"ORDER BY updated_at DESC LIMIT %s",
(tenant_id, since, 20))
for row in cur.fetchall():
print(row["id"], row["title"])A row factory such as dict_row returns rows as dictionaries instead of tuples. fetchone, fetchmany and fetchall retrieve results; for very large results, a named (server-side) cursor streams rows instead of loading them all into memory.
Queries and results
Transactions and bulk operations
In psycopg, statements run inside a transaction that starts automatically. Using the connection in a with block commits when the block ends normally and rolls back if an exception escapes, so a set of related changes, such as replacing all chunks of a document, either fully happens or does not happen at all. conn.transaction() creates explicit transaction blocks, including nested savepoints.
Round trips dominate the cost of loading many rows. Instead of one INSERT per chunk, use executemany, which batches statements, or COPY, PostgreSQL's bulk-load protocol, which is the fastest way to load thousands of rows. pgvector's Python package, pgvector, registers the vector type with psycopg so that NumPy arrays and lists can be passed directly.
from pgvector.psycopg import register_vector
with connect() as conn:
register_vector(conn)
with conn.transaction():
conn.execute("DELETE FROM chunks WHERE document_id = %s", (doc_id,))
with conn.cursor().copy("COPY chunks (document_id, position, content, embedding) FROM STDIN") as copy:
for position, (text, vector) in enumerate(zip(texts, vectors)):
copy.write_row((doc_id, position, text, vector))The following diagram compares the original script with the corrected one.

Transactions and bulk loads
An ingestion job that is slow and unsafe
An ingestion script builds INSERT statements with f-strings, such as f"INSERT INTO chunks VALUES ({doc_id}, '{text}', ...)", and commits after every row. Loading 200,000 chunks takes over an hour, and documents containing apostrophes fail to load. The script connects with a password copied into its configuration file.
Three changes fix it. Use parameters instead of f-strings, which removes both the quoting failures and the injection risk. Load each document's chunks with COPY or executemany inside one transaction per document, which removes most round trips and commits. And connect with a Microsoft Entra token from DefaultAzureCredential, so that no password is stored.
Escaping apostrophes by hand would fix one symptom while leaving the injection risk. Raising the server's tier would not remove the per-row round trips. Disabling TLS would not speed the load meaningfully and weakens security.
An application connects to PostgreSQL with a Microsoft Entra token. Why does an already open connection keep working after the token expires?
Show answer
Tokens are checked only when a connection is opened. New connections, including those a pool opens later, need a fresh token.
Exam Tips
Remember for the exam
- Use psycopg with sslmode=require; keep connection details in configuration.
- Entra tokens for scope https://ossrdbms-aad.database.windows.net/.default replace passwords; fetch one per new connection.
- Always pass values as parameters, never by string formatting.
- Load bulk data with COPY or executemany inside a transaction.