Connect JDBC to a PostgreSQL-dialect database

This page explains how to connect the PostgreSQL JDBC driver to a PostgreSQL-dialect database in Cloud Spanner. JDBC is the standard Java driver for PostgreSQL.

  1. Ensure that PGAdapter is running on the same machine as the application that is connecting using the PostgreSQL JDBC driver.

    For more information, see Start PGAdapter.

  2. Specify localhost and 5432 as the database server host and port in the JDBC connection string.

    • Optionally specify a different port number if PGAdapter is configured to listen on a port other than the default PostgreSQL port (5432).
    // 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));
       }
     }
    }
    

What's next