将 psycopg3 连接到 PostgreSQL 方言数据库

本页面介绍了如何将 PostgreSQL psycopg3 驱动程序连接到 Spanner 中的 PostgreSQL 方言数据库。psycopg3 是 PostgreSQL 的 Python 驱动程序。

  1. 验证 PGAdapter 是否与使用 PostgreSQL psycopg3 驱动程序进行连接的应用位于同一台机器上。

    export GOOGLE_APPLICATION_CREDENTIALS=/CREDENTIALS_FILE_PATH/credentials.json
    docker pull gcr.io/cloud-spanner-pg-adapter/pgadapter
    docker run \
      -d -p 5432:5432 \
      -v ${GOOGLE_APPLICATION_CREDENTIALS}:${GOOGLE_APPLICATION_CREDENTIALS}:ro \
      -e GOOGLE_APPLICATION_CREDENTIALS \
      gcr.io/cloud-spanner-pg-adapter/pgadapter \
      -p PROJECT_NAME -i INSTANCE_NAME \
      -x
    

    如需了解详情,请参阅启动 PGAdapter

  2. 使用 TCP 连接到 PGAdapter。

    import psycopg
    
    with psycopg.connect("host=APPLICATION_HOST port=PORT dbname=DATABASE_NAME sslmode=disable") as conn:
      conn.autocommit = True
      with conn.cursor() as cur:
        cur.execute("select 'Hello world!' as hello")
        print("Greeting from Cloud Spanner PostgreSQL:", cur.fetchone()[0])
    

    替换以下内容:

    • APPLICATION_HOST:运行 PGAdapter 的机器的主机名或 IP 地址。如果在本地运行,请使用 localhost
    • PORT:PGAdapter 运行的端口号。如果 PGAdapter 在自定义端口上运行,请在连接字符串中更改此设置。否则,请使用默认端口 5432

Unix 网域套接字

本部分介绍如何使用 Unix 域套接字连接到 PostgreSQL 方言数据库。使用 Unix 网域套接字可实现尽可能低的延迟时间。

如需使用 Unix 域套接字,PGAdapter 必须与客户端应用在同一主机上运行。

验证 PostgreSQL JDBC 驱动程序是否已加载。

import psycopg

with psycopg.connect("host=/tmp
                      port=PORT
                      dbname=DATABASE_NAME") as conn:
conn.autocommit = True
with conn.cursor() as cur:
  cur.execute("select 'Hello world!' as hello")
  print("Greetings from Cloud Spanner PostgreSQL:", cur.fetchone()[0])

替换以下内容:

  • /tmp:PGAdapter 的默认网域套接字目录。您可以使用 -dir 命令行实参更改此设置。
  • PORT:PGAdapter 运行的端口号。如果 PGAdapter 在自定义端口上运行,请在连接字符串中更改此设置。否则,请使用默认端口 5432

后续步骤

  • 详细了解 PGAdapter
  • 如需详细了解 PostgreSQL psycopg3 驱动程序连接选项,请参阅 PGAdapter GitHub 代码库中的 psycopg3 连接选项