Cloud Spanner Client Libraries

Cloud Spanner Client Libraries

This page shows how to get started with the new Cloud Client Libraries for the Cloud Spanner API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

The Cloud Spanner Client Libraries mentioned on this page are supported on Google Compute Engine (GCE), Google App Engine - Flexible Environment, and Google Container Engine (GKE). If you are using Google App Engine - Standard Environment, please access Cloud Spanner using the REST Interface, instead of the client libraries.

Installing the client library

Go

go get -u cloud.google.com/go/spanner/...

Java

If you are using Maven, add this to your pom.xml file:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-spanner</artifactId>
    <version>0.9.4-beta</version>
</dependency>

If you are using Gradle, add this to your dependencies:

compile group: 'com.google.cloud', name: 'google-cloud-spanner', version: '0.9.4-beta'

Node.js

npm install --save @google-cloud/spanner

Python

pip install --upgrade google-cloud-spanner

Using the client library

Here's an example of how to use the client library. To run it on your local workstation you must first install the Google Cloud SDK and authenticate by running the following command:

gcloud auth application-default login

For information about authenticating in other environments, see the Google Cloud Platform Auth Guide.

Go

package main

import (
	"fmt"
	"log"

	"cloud.google.com/go/spanner"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()

	// This database must exist.
	databaseID := "projects/your-project-id/instances/your-instance-id/databases/your-database-id"

	client, err := spanner.NewClient(ctx, databaseID)
	if err != nil {
		log.Fatalf("Failed to create client %v", err)
	}
	defer client.Close()

	stmt := spanner.Statement{SQL: "SELECT 1"}
	iter := client.Single().Query(ctx, stmt)
	defer iter.Stop()

	row, err := iter.Next()
	if err != nil {
		log.Fatalf("Query failed with %v", err)
	}

	var i int64
	if row.Columns(&i) != nil {
		log.Fatalf("Failed to parse row %v", err)
	}
	fmt.Printf("Got value %v\n", i)
}
Read more in the Go API Reference Documentation for the Cloud Spanner API Client Library.

Java

// Imports the Google Cloud client library
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;

/**
 * A quick start code for Cloud Spanner. It demonstrates how to setup the Cloud Spanner client and
 * execute a simple query using it against an existing database.
 */
public class QuickstartSample {
  public static void main(String... args) throws Exception {

    if (args.length != 2) {
      System.err.println("Usage: QuickStartSample <instance_id> <database_id>");
      return;
    }
    // Instantiates a client
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();

    // Name of your instance & database.
    String instanceId = args[0];
    String databaseId = args[1];
    try {
      // Creates a database client
      DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(
          options.getProjectId(), instanceId, databaseId));
      // Queries the database
      ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));

      System.out.println("\n\nResults:");
      // Prints the results
      while (resultSet.next()) {
        System.out.printf("%d\n\n", resultSet.getLong(0));
      }
    } finally {
      // Closes the client which will free up the resources used
      spanner.closeAsync().get();
    }
  }
}
Read more in the Java API Reference Documentation for the Cloud Spanner API Client Library.

Node.js

// Imports the Google Cloud client library
const Spanner = require('@google-cloud/spanner');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const spanner = Spanner({
  projectId: projectId
});

// Your Cloud Spanner instance ID
const instanceId = 'my-instance';

// Your Cloud Spanner database ID
const databaseId = 'my-database';

// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);

// The query to execute
const query = {
  sql: 'SELECT 1'
};

// Execute a simple SQL statement
database.run(query)
  .then((results) => {
    const rows = results[0];

    rows.forEach((row) => console.log(row));
  });
Read more in the Node.js API Reference Documentation for the Cloud Spanner API Client Library.

Python

# Imports the Google Cloud Client Library.
from google.cloud import spanner

# Instantiate a client.
spanner_client = spanner.Client()

# Your Cloud Spanner instance ID.
instance_id = 'my-instance-id'

# Get a Cloud Spanner instance by ID.
instance = spanner_client.instance(instance_id)

# Your Cloud Spanner database ID.
database_id = 'my-database-id'

# Get a Cloud Spanner database by ID.
database = instance.database(database_id)

# Execute a simple SQL statement.
results = database.execute_sql('SELECT 1')

for row in results:
    print(row)
Read more in the Python API Reference Documentation for the Cloud Spanner API Client Library.

Additional Resources

Send feedback about...

Cloud Spanner Documentation