将 psycopg2 连接到 PostgreSQL 方言数据库

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

  1. 确保 PGAdapter 与使用 PostgreSQL psycopg2 驱动程序进行连接的应用在同一机器上运行。

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

  2. psycopg2 连接属性中,将 localhost5432 指定为数据库服务器主机和端口。

    • (可选)如果 PGAdapter 配置为在默认 PostgreSQL 端口 (5432) 以外的端口上进行监听,则请指定其他端口号。
    • (可选)如果 PGAdapter 在不同于本地机器的主机上运行,请指定不同的主机名。
    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()
    

后续步骤

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