Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 14 of 28
❮Prev Next❯

Connect to and Query Azure Database for PostgreSQL

Module 2: Data for AI ⏱ 10 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    You connect to Azure Database for PostgreSQL flexible server from Python with psycopg (version 3). Instead of a stored password, you get a Microsoft Entra token from DefaultAzureCredential for the scope https://ossrdbms-aad.database.windows.net/.default and pass it as the password, with your Entra user or managed identity name as the user and sslmode=require. Then you run SQL with parameterised queries (%s placeholders), never by pasting user input into the SQL string.

    Simulate it » No Azure account needed

    Exam objective: 2.2.1 Connect and query Azure Database for PostgreSQL by using SDKs. (Skills measured as of October 7, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Create a PostgreSQL flexible server with Entra sign-in Create a flexible server with Microsoft Entra authentication.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Search for <strong>postgres</strong> in the top bar.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Search for postgres in the top bar.
    2. Type postgres and pick Azure Database for PostgreSQL flexible servers under Services.
    3. Select + Create.
    4. Pick Microsoft Entra authentication only: no database password to leak. Set yourself as the Entra admin.
    5. For a lab, public access with your own IP is fine. Production apps usually use private access in a VNet.
    6. Review and Create. It takes about five minutes.
    7. Connect with an Entra access token as the password. Your Python app does the same with DefaultAzureCredential.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    Your Python app stores the database password in plain text.

    😊 THE SOLUTION

    Connect with psycopg and a Microsoft Entra token instead.

    • Passwords in config✓ Entra ID tokens
    • SQL injection✓ Parameterised queries
    • Connection per request✓ A connection pool
    🛠️ Solved with: PostgreSQL from Python

    Start with a question

    Your app needs to read from a database. Do you really have to paste the database password into a config file?

    Think about a staff canteen. Some offices hand out a paper coupon that anyone can copy. Others let you tap your ID card, and the card only works while you still work there.

    A database password in config.py is the paper coupon. It gets committed to git, pasted into Teams and left on old laptops. Microsoft Entra authentication is the ID card: your app proves who it is, gets a short-lived token, and uses that as the password. Nobody has a secret to leak.

    This lesson shows how a Python app connects to Azure Database for PostgreSQL that way and then runs queries safely.

    Explain it like I’m 10

    The technical explanation

    Azure Database for PostgreSQL flexible server is managed PostgreSQL. Microsoft patches it, backs it up and can run a standby for high availability. You still write normal SQL and use normal PostgreSQL drivers. For Python that’s psycopg version 3:

    pip install "psycopg[binary]" psycopg_pool azure-identity

    What a connection needs

    SettingExampleNotes
    hostcontoso-pg.postgres.database.azure.comFrom the server’s Overview page
    port54326432 if you go through the built-in PgBouncer
    dbnamesupportA database on the server
    userrag-api (an Entra identity) or pgadminThe role name in PostgreSQL
    passwordan Entra token, or a database passwordToken preferred
    sslmoderequireRefuses to connect without TLS

    Passwordless sign-in with Microsoft Entra ID

    Two things have to be set up on the server first. The server’s authentication must allow Microsoft Entra (the portal option is “Microsoft Entra authentication only” or “PostgreSQL and Microsoft Entra authentication”). And an Entra admin must create a database role for your user, group or managed identity.

    Then your code asks for a token and uses it as the password:

    import os
    import psycopg
    from azure.identity import DefaultAzureCredential
    
    credential = DefaultAzureCredential()
    
    def get_token() -> str:
        # Token for Azure Database for PostgreSQL
        return credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
    
    conn = psycopg.connect(
        host=os.environ["PGHOST"],          # contoso-pg.postgres.database.azure.com
        dbname=os.environ["PGDATABASE"],    # support
        user=os.environ["PGUSER"],          # rag-api (the managed identity's role name)
        password=get_token(),
        port=5432,
        sslmode="require",
    )

    DefaultAzureCredential uses your az login session on your laptop and the app’s managed identity in App Service, Container Apps or Functions. Same code, no secret.

    The token is checked only when a connection opens. An open connection keeps working after the token expires, but any new connection needs a fresh token. That matters once you add a pool, which you’ll see below and in the performance lesson.

    Running queries safely

    tenant = "contoso"
    search = "refund"
    
    with conn:                                   # commits on success, rolls back on error
        with conn.cursor() as cur:
            cur.execute(
                "SELECT id, title FROM docs WHERE tenant_id = %s AND title ILIKE %s LIMIT 10",
                (tenant, f"%{search}%"),         # values travel separately from the SQL
            )
            for row in cur.fetchall():
                print(row)
    
            cur.execute(
                "INSERT INTO docs (tenant_id, title, body) VALUES (%(t)s, %(title)s, %(body)s) RETURNING id",
                {"t": tenant, "title": "Refund policy", "body": "Refunds within 30 days..."},
            )
            new_id = cur.fetchone()[0]

    The %s and %(name)s placeholders are the whole point. psycopg sends the SQL text and the values separately, so a value like '; DROP TABLE docs; -- is just a strange title, not a command. This is called a parameterised query, and it’s the answer to SQL injection.

    For many rows at once, cur.executemany(sql, rows) reuses the same statement, and cur.copy() with COPY ... FROM STDIN is the fastest way to bulk-load, which you’ll want when loading thousands of embeddings.

    Reusing connections

    Opening a PostgreSQL connection costs a TLS handshake, sign-in and a new server process. A web API that opens one per request spends more time connecting than querying. Use a pool, and give it a connection class that gets a fresh token every time it opens a connection:

    from psycopg_pool import ConnectionPool
    
    class EntraConnection(psycopg.Connection):
        @classmethod
        def connect(cls, conninfo="", **kwargs):
            kwargs["password"] = get_token()     # fresh token for every new connection
            return super().connect(conninfo, **kwargs)
    
    pool = ConnectionPool(
        conninfo=f"host={os.environ['PGHOST']} dbname=support user=rag-api sslmode=require",
        connection_class=EntraConnection,
        min_size=2, max_size=10,
    )
    
    with pool.connection() as conn:
        print(conn.execute("SELECT version()").fetchone())
    1. 1 Get a token

      DefaultAzureCredential asks Entra ID for the ossrdbms-aad scope.

    2. 2 Connect

      psycopg opens a TLS connection with the token as the password.

    3. 3 Map the role

      PostgreSQL matches the Entra identity to a database role.

    4. 4 Query

      Parameterised SQL runs, and rows come back.

    From your code to a row of data
    Architect level Network access decides whether you can connect at all

    Flexible server has two networking models, chosen at creation. Public access gives the server a public endpoint protected by firewall rules (and you can add private endpoints). Private access (VNet integration) puts the server inside a delegated subnet with no public endpoint, and your app must reach that VNet. If the connection times out, it’s almost always networking. If it’s refused with “password authentication failed”, it’s the token, the user name or a missing role. Knowing which error means what saves a lot of time.

    Real-world business scenario

    Insurance

    Fabrikam Insurance (fictional)

    The problem
    A claims assistant built in Python read policy documents from PostgreSQL using a shared admin password stored in an app setting. A contractor copied it into a test script that later ended up in a public repository.
    What they used
    Azure Database for PostgreSQL flexible server with Microsoft Entra authentication, a managed identity for the API, psycopg 3 with parameterised queries and a pool that fetches a fresh token per connection.
    Why that choice
    There's no password to copy any more, and access is removed by deleting the database role or the identity. Parameterised queries close the injection hole the security review flagged.
    The result
    The shared password was retired, and the security team can see exactly which identity ran each session in the server logs.

    When to use it and when not to

    ✓ Use it when…

    • Your app runs in Azure (App Service, Container Apps, Functions, AKS) and can use a managed identity.
    • You want access controlled by Entra users and groups instead of database passwords.
    • You run any query that includes user input. Parameterise it every time.

    ✕ Think twice when…

    • An old tool that only accepts a short password field and can't take a token. Use a database password stored in Key Vault for that one tool.
    • Opening a new connection for every request in a busy API. Use a pool or PgBouncer.

    ↔ Alternatives to consider

    • PostgreSQL password authentication with the secret in Azure Key Vault, when Entra isn't possible.
    • Azure Cosmos DB for NoSQL when your data is JSON documents and you want global scale without SQL joins.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    A Python application that runs in Azure Container Apps must connect to an Azure Database for PostgreSQL flexible server without storing a password. The application uses a managed identity. What should the application pass as the password when it opens the connection?

    Question 2

    Question 2 of 5

    A developer writes the following code: cur.execute(f"SELECT * FROM docs WHERE title = '{user_input}'"). A security review flags the line. Which change resolves the issue?

    Question 3

    Question 3 of 5

    A web API uses psycopg_pool and Microsoft Entra authentication to connect to Azure Database for PostgreSQL. The API works after deployment, but after about an hour new connections fail with an authentication error while existing connections continue to work. What is the most likely cause?

    Question 4

    Question 4 of 5 · Select 2

    You plan to connect a Python application to Azure Database for PostgreSQL flexible server by using Microsoft Entra authentication. Which TWO actions are required before the application can sign in?

    Question 5

    Question 5 of 5

    A developer must ensure that a psycopg connection to Azure Database for PostgreSQL is never established without encryption. Which connection setting should the developer specify?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner What do you need to connect a Python app to Azure Database for PostgreSQL?

    Model answer

    The server host name (something like myserver.postgres.database.azure.com), the database name, a user, a password or token, port 5432 and TLS. In Python I use psycopg 3. For the password I prefer a Microsoft Entra token from DefaultAzureCredential, so there's no secret in my config.

    Interviewer follows up

    What is the user name when you sign in with a managed identity?

    You

    It's the name of the Entra principal that was mapped to a database role, for example the managed identity's name. An Entra admin creates that role first.

    Intermediate Why do you pass values with %s instead of building the SQL string with an f-string?

    Model answer

    Because an f-string mixes data into the SQL text. If a user types something like a quote and a DROP TABLE, it becomes part of the query. With %s, psycopg sends the values separately from the SQL, so input is always treated as data. It's the fix for SQL injection.

    Experienced developer Entra tokens expire. How do you stop a long-running app from failing an hour after it starts?

    Model answer

    The token only matters when a connection is opened, so I fetch a fresh token every time a new connection is made. With psycopg_pool I give the pool a small connection class whose connect method asks DefaultAzureCredential for a token, and I keep max_lifetime under the token lifetime. Open connections stay valid; new ones get new tokens.

    Scenario Your app connects fine from your laptop but times out from a new App Service. What would you check first?

    Model answer

    Networking. With public access I'd check the server firewall rules allow the App Service outbound IPs or Azure services. With private access I'd check the App Service has VNet integration into a subnet that can reach the server and that private DNS resolves the host name. A timeout usually means network, while a wrong token gives an authentication error.

    Quick revision

    Key points

    • Use psycopg 3 (import psycopg) with host, dbname, user, password, port 5432 and sslmode=require.
    • For passwordless sign-in, DefaultAzureCredential gets a token for https://ossrdbms-aad.database.windows.net/.default and you pass it as the password.
    • An Entra admin on the server must create a database role for each Entra user, group or managed identity.
    • Always use %s placeholders and pass values as a tuple or dict. Never format user input into SQL.
    • Use with blocks so connections commit or roll back and close cleanly.

    Important terminology

    Azure Database for PostgreSQL flexible server
    The managed PostgreSQL service on Azure, where Microsoft runs patching, backups and high availability while you choose compute and storage.
    psycopg
    The most used PostgreSQL driver for Python. Version 3 is imported as psycopg and adds a separate psycopg_pool package for pooling.
    Microsoft Entra authentication
    Signing in to PostgreSQL with an Entra access token as the password instead of a database password.
    ossrdbms-aad scope
    The token scope https://ossrdbms-aad.database.windows.net/.default used to request tokens for Azure Database for PostgreSQL.
    sslmode=require
    A connection setting that makes the client refuse to connect without TLS encryption.
    Parameterised query
    SQL with placeholders such as %s, where the driver sends the values separately so user input can't change the query.

    Common mistakes

    • Building SQL with f-strings or + from user input, which opens the door to SQL injection.
    • Fetching one token at start-up and reusing it for every new connection after it has expired.
    • Leaving sslmode out and assuming the client will always pick TLS.

    Exam tips

    • "Connect without storing a password" = Microsoft Entra token from DefaultAzureCredential used as the password.
    • "Token scope for PostgreSQL" = https://ossrdbms-aad.database.windows.net/.default.
    • "Prevent SQL injection" = parameterised queries (%s placeholders), not string formatting.

    Five quick revision questions

    1. 1.Which Python driver is used in the samples for PostgreSQL?Show

      psycopg (version 3).

    2. 2.What scope do you request a token for?Show

      https://ossrdbms-aad.database.windows.net/.default

    3. 3.Where does the token go in the connection?Show

      In the password field.

    4. 4.Which setting forces TLS?Show

      sslmode=require.

    5. 5.What's the default PostgreSQL port?Show

      5432 (PgBouncer uses 6432).

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: PostgreSQL Schemas, Data Types and Indexes

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.