Use the Spanner database/sql driver

Go database/sql is a generic interface around SQL (or SQL-like) databases for the Go programming language. To use database/sql with your application, use the Spanner database/sql driver.

Install the Spanner database/sql driver

To use the Spanner database/sql driver in your application, add the following module to your go.mod file:

  github.com/googleapis/go-sql-spanner

Use the Spanner database/sql driver

To create a database/sql connection to a Spanner database, use spanner as the driver name and a fully qualified database name as the connection string:

import (
	"database/sql"
	"fmt"

	_ "github.com/googleapis/go-sql-spanner"
)

func connect(projectId, instanceId, databaseId string) error {
	dsn := fmt.Sprintf("projects/%s/instances/%s/databases/%s", projectId, instanceId, databaseId)
	db, err := sql.Open("spanner", dsn)
	if err != nil {
		return fmt.Errorf("failed to open database connection: %v", err)
	}
	defer func() { _ = db.Close() }()

	fmt.Printf("Connected to %s\n", dsn)

	return nil
}

For more information, see the Spanner database/sql driver GitHub repository.

Supported features

The Spanner Go database/sql examples code directory contains ready-to-run examples for commonly used Spanner features.

Performance tips

To get the best possible performance when using the Spanner database/sql driver, follow these best practices:

What's next