Connect psycopg2 to a PostgreSQL-dialect database

This page explains how to connect the PostgreSQL psycopg2 driver to a PostgreSQL-dialect database in Spanner. psycopg2 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 psycopg2 driver.

    For more information, see Start PGAdapter.

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

    • Optionally specify a different port number if PGAdapter is configured to listen on a port other than the default PostgreSQL port (5432).
    • Optionally specify a different host name if PGAdapter is running on a different host than the local machine.
    connection = psycopg2.connect(database="database_name",
                                 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