将 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 连接选项