将 psycopg2 连接到 PostgreSQL 方言数据库

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

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

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

connection = psycopg2.connect(database="DATABASE_NAME",
                              host="APPLICATION_HOST",
                              port=PORT)

cursor = connection.cursor()
cursor.execute('select \'Hello World\'')
for row in cursor:
  print(row)

cursor.close()
connection.close()

替换以下内容:

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

Unix 网域套接字

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

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

connection = psycopg2.connect(database="DATABASE_NAME",
                              host="/tmp",
                              port=PORT)

cursor = connection.cursor()
cursor.execute('select \'Hello World\'')
for row in cursor:
  print(row)

cursor.close()
connection.close()

替换以下内容:

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

后续步骤

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