Launch price: every exam for $29.99 a year, for the first 300 buyers. See the price

CertStreak
Menu

Connect and query Azure Database for PostgreSQL by using SDKs

A worked example

Complete the statement

A Python service uses psycopg (version 3) to read messages from an Azure Database for PostgreSQL flexible server. The conninfo string already sets sslrootcert to a file that contains the trusted root CA certificates. The code must meet these requirements:

  1. The connection must be encrypted. The client must validate that the server certificate is signed by a trusted certificate authority, and it must confirm that the certificate hostname matches the server.
  2. The conversation_id value comes from user input and must be passed to the query in a way that prevents SQL injection.
  3. The retry loop must retry connection and timeout failures while allowing constraint violations and SQL syntax errors to propagate.

How should you complete the code?

import time
import psycopg

for attempt in range(5):
    try:
        with psycopg.connect(conninfo, sslmode="", connect_timeout=10) as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "SELECT role, content FROM messages WHERE conversation_id = ",
                    (conversation_id,))
                rows = cur.fetchall()
        break
    except psycopg.errors.:
        time.sleep(2 ** attempt)
  • Blank 1: verify-full (correct answer)

    verify-full requires encryption and checks both the certificate's CA trust and its hostname, meeting requirement 1. Neither require nor verify-ca checks the hostname. prefer does not enforce encryption or validate the certificate.

  • Blank 2: %s (correct answer)

    psycopg uses %s for positional parameters, which it binds from the tuple passed to execute(). This lets the driver handle escaping and prevents SQL injection. ? is not a psycopg placeholder. :conversation_id is not a psycopg placeholder; the named form psycopg uses is %(name)s with a mapping. {} is Python string-formatting syntax, and building queries with string formatting is the pattern to avoid.

  • Blank 3: OperationalError (correct answer)

    OperationalError catches connection and timeout failures while allowing constraint violations and SQL syntax errors to propagate. UniqueViolation, CheckViolation and ForeignKeyViolation each catch a constraint violation instead, so none implements the required retry behavior.

Why

verify-full checks CA trust and the server hostname while requiring encryption. The %s placeholder binds conversation_id separately from the SQL text. Catching OperationalError handles connection and timeout failures, while constraint violations and syntax errors propagate. Those excluded errors need correction rather than an unchanged retry.

Practise this topic until it's automatic.

Ten questions a day, every answer explained, and misses that come back until you beat them.

Start free