Connect pgx to a PostgreSQL-dialect database

This page explains how to connect the PostgreSQL pgx driver to a PostgreSQL-dialect database in Spanner. pgx is a Golang driver for PostgreSQL.

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

    For more information, see Start PGAdapter.

  2. Specify localhost and 5432 as the database server host and port in the pgx connection string. pgx requires a username and password in the connection string. PGAdapter ignores these.

    • Optionally specify a different port number if PGAdapter is configured to listen on a port other than the default PostgreSQL port (5432).
    • By default, PGAdapter disables SSL. pgx by default first tries to connect with SSL enabled. Disabling SSL in the connection request speeds up the connection process, as it requires one fewer round trip.
    connString := "postgres://uid:pwd@localhost:5432/my-database?sslmode=disable"
    ctx := context.Background()
    conn, err := pgx.Connect(ctx, connString)
    if err != nil {
      return err
    }
    defer conn.Close(ctx)
    
    var greeting string
    err = conn.QueryRow(ctx, "select 'Hello world!' as hello").Scan(&greeting)
    if err != nil {
      return err
    }
    fmt.Printf("Greeting from Cloud Spanner PostgreSQL: %v\n", greeting)
    

What's next