Connect and query Azure Database for PostgreSQL with SDKs
Unlock the complete study guide + 1,040 practice questions across 16 full exams.
Bundled into the existing Developing AI Cloud Solutions on Azure premium course — no separate purchase.
14-day money-back guarantee — no questions asked.
Included in this chapter:
- How a Python client reaches flexible server
- Choosing a driver: psycopg, asyncpg, or SQLAlchemy
- Building the connection string
- TLS and what sslmode actually verifies
- Authenticating with Microsoft Entra ID
- Passing parameters safely
- Reading results back
- How long your state lives: transaction and session scope
- Streaming large result sets with a server-side cursor
Python PostgreSQL drivers on the axes that change your code
| Property | psycopg2 | psycopg 3 | asyncpg |
|---|---|---|---|
| Placeholder syntax | %s and %(name)s | %s and %(name)s | $1, $2 (positional) |
| Concurrency model | Synchronous only | Synchronous and asyncio in one package | asyncio only |
| Where parameters are bound | Merged into the statement on the client | Sent to the server separately from the statement | Sent to the server separately from the statement |
| Prepared statements | Only if you write PREPARE yourself | Automatic after prepare_threshold executions on a connection | Automatic through the statement cache |
| Client-side pool | Basic pools in psycopg2.pool | psycopg_pool, a separately distributed package | asyncpg.create_pool(), part of the driver |
| SQLAlchemy dialect prefix | postgresql+psycopg2:// | postgresql+psycopg:// | postgresql+asyncpg:// |
Decision tree
Cheat sheet
Unlock with Premium — includes all practice exams and the complete study guide.
References
- PgBouncer in Azure Database for PostgreSQL flexible server
- Connection libraries in Azure Database for PostgreSQL flexible server
- Quickstart: Use Python to connect and query data in Azure Database for PostgreSQL flexible server
- asyncpg: a fast PostgreSQL client library for Python/asyncio
- SQLAlchemy 2.0: PostgreSQL dialect
- psycopg 3: differences from psycopg2
- PostgreSQL: libpq connection strings and parameter keywords
- Quickstart: Connect and query by using Azure CLI in Azure Database for PostgreSQL flexible server
- Transport Layer Security (TLS) in Azure Database for PostgreSQL flexible server
- asyncpg: API reference
- Use Microsoft Entra ID authentication in Azure Database for PostgreSQL flexible server
- Connect with managed identity in Azure Database for PostgreSQL flexible server
- Microsoft Entra authentication in Azure Database for PostgreSQL flexible server
- psycopg 3: passing parameters to SQL queries
- asyncpg: usage
- psycopg 3: cursor classes
- psycopg 3: transactions management
- psycopg 3: prepared statements
- asyncpg: frequently asked questions FAQ
- psycopg 3: cursor types
- PostgreSQL: DECLARE