将 JDBC 连接到 PostgreSQL 方言数据库

您可以将 PostgreSQL JDBC 驱动程序和 Spanner JDBC 驱动程序与 Spanner PostgreSQL 方言数据库一起使用。本页面介绍了如何使用上述任一驱动程序连接到您的数据库。

PostgreSQL JDBC 驱动程序

本部分介绍如何将 PostgreSQL JDBC 驱动程序连接到 Spanner 中的 PostgreSQL 方言数据库。JDBC 是 PostgreSQL 的标准 Java 驱动程序。

如需使用 PostgreSQL JDBC 驱动程序,您需要使用 PGAdapter 在 PostgreSQL 网络协议和 Spanner 网络协议之间进行转换。您可以将 PGAdapter 添加为依赖项,并在应用进程内运行它。

1. 将 PGAdapter 和 PostgreSQL JDBC 驱动程序作为依赖项添加到您的应用。

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>0.32.0</version>
</dependency>
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-spanner-pgadapter</artifactId>
  <version>0.32.0</version>
</dependency>

2. 在应用中启动 PGAdapter。

OptionsMetadata.Builder builder =
    OptionsMetadata.newBuilder()
        .setProject("my-project")
        .setInstance("my-instance")
        // Set the port to 0 to use a dynamically assigned port.
        .setPort(5432);
ProxyServer server = new ProxyServer(builder.build());
server.startServer();
server.awaitRunning();
      

3. 在 JDBC 连接字符串中指定 localhost5432 作为数据库服务器主机和端口。

// Make sure the PG JDBC driver is loaded.
Class.forName("org.postgresql.Driver");

// Replace localhost and 5432 with the host and port number where PGAdapter is running.
try (Connection connection =
    DriverManager.getConnection("jdbc:postgresql://localhost:5432/my-database")) {
  try (ResultSet resultSet =
      connection.createStatement().executeQuery("select 'Hello world!' as hello")) {
    while (resultSet.next()) {
      System.out.printf(
        "Greeting from Cloud Spanner PostgreSQL: %s\n", resultSet.getString(1));
    }
  }
}
      

PGAdapter GitHub 代码库包含一个 可正常运行的示例应用。

Spanner JDBC 驱动程序

本部分介绍如何使用 Spanner JDBC 驱动程序连接到 PostgreSQL 方言数据库数据库。

1. 将 Spanner JDBC 驱动程序作为依赖项添加到应用中。

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.37.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-spanner-jdbc</artifactId>
  </dependency>

2. 使用 Spanner JDBC 连接网址连接到 PostgreSQL 方言数据库。

try (Connection connection = DriverManager.getConnection(
    "jdbc:cloudspanner:/projects/my-project/instances/my-instance/databases/my-database")) {
  try (ResultSet resultSet =
      connection.createStatement().executeQuery("select 'Hello world!' as hello")) {
    while (resultSet.next()) {
      System.out.printf(
        "Greeting from Cloud Spanner PostgreSQL: %s\n", resultSet.getString(1));
    }
  }
}
        

驱动程序会自动检测指定数据库的 SQL 方言。 连接网址中不需要包含方言参数。

后续步骤