Connect psycopg3 to a PostgreSQL-dialect database

This page explains how to connect the PostgreSQL psycopg3 driver to a PostgreSQL-dialect database in Spanner. psycopg3 is a Python driver for PostgreSQL.

  1. Ensure that PGAdapter is running on the same machine as the application that is connecting using the PostgreSQL psycopg3 driver.

    For more information, see Start PGAdapter.

  2. Specify localhost and 5432 as the database server host and port in the psycopg3 connection properties.

    • Optional: Specify a different port number if PGAdapter is configured to listen on a port other than the default PostgreSQL port (5432).
    • Optional: Specify a different host name if PGAdapter is running on a different host than the local machine.
    connection = psycopg.connect(database="DATABASE_ID",
                                 host="localhost",
                                 port=5432)
    
    cursor = connection.cursor()
    cursor.execute('select \'Hello World\'')
    for row in cursor:
     print(row)
    
    cursor.close()
    connection.close()

What's next