JDBC を PostgreSQL 言語データベースに接続する

Spanner PostgreSQL 言語データベースでは、PostgreSQL JDBC ドライバと Spanner JDBC ドライバの両方を使用できます。このページでは、これらのドライバのいずれかを使用してデータベースに接続する方法について説明します。

PostgreSQL JDBC ドライバ

このセクションでは、Spanner で PostgreSQL JDBC ドライバを PostgreSQL 言語データベースに接続する方法について説明します。JDBC は PostgreSQL の標準 Java ドライバです。

PostgreSQL JDBC ドライバを使用するには、PGAdapter を使用して PostgreSQL ネットワーク プロトコルと Spanner ネットワーク プロトコルの変換を行う必要があります。PGAdapter を依存関係として追加し、アプリケーションを使用してプロセス内で実行できます。

1. PGAdapter と PostgreSQL JDBC ドライバを依存関係としてアプリケーションに追加します。

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>0.33.1</version>
</dependency>
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-spanner-pgadapter</artifactId>
  <version>0.33.1</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.39.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 接続 URL を使用して 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 言語を自動的に検出します。接続 URL に言語パラメータは必要ありません。

次のステップ