Spanner client libraries
Stay organized with collections
Save and categorize content based on your preferences.
This page shows how to get started with the Cloud Client Libraries for the
Cloud Spanner API. Client libraries make it easier to access
Google Cloud APIs from a supported language. Although you can use
Google Cloud APIs directly by making raw requests to the server, client
libraries provide simplifications that significantly reduce the amount of code
you need to write.
Read more about the Cloud Client Libraries
and the older Google API Client Libraries in
Client libraries explained.
Spanner provides client libraries for popular programming languages,
including C++, C#, Go, Java, Node.js, PHP, Python, and Ruby. The client
libraries connect to the Spanner service using gRPC over a
TLS-encrypted HTTP/2 connection, so you don't need to manually configure SSL or
TLS.
The Spanner client libraries are supported on Compute Engine,
App Engine flexible environment, Google Kubernetes Engine, and Cloud Run functions.
The Spanner client library for Java is also supported on
App Engine standard environment with Java 8.
If you are using the App Engine standard environment with Go, PHP, or
Python, use the REST interface to access
Spanner.
To authenticate calls to Google Cloud APIs, client libraries support
Application Default Credentials (ADC);
the libraries look for credentials in a set of defined locations and use those credentials
to authenticate requests to the API. With ADC, you can make
credentials available to your application in a variety of environments, such as local
development or production, without needing to modify your application code.
For production environments, the way you set up ADC depends on the service
and context. For more information, see Set up Application Default Credentials.
For a local development environment, you can set up ADC with the credentials
that are associated with your Google Account:
Install the Google Cloud CLI.
After installation,
initialize the Google Cloud CLI by running the following command:
usingGoogle.Cloud.Spanner.Data;usingSystem;usingSystem.Threading.Tasks;namespaceGoogleCloudSamples.Spanner{publicclassQuickStart{staticasyncTaskMainAsync(){stringprojectId="YOUR-PROJECT-ID";stringinstanceId="my-instance";stringdatabaseId="my-database";stringconnectionString=$"Data Source=projects/{projectId}/instances/{instanceId}/"+$"databases/{databaseId}";// Create connection to Cloud Spanner.using(varconnection=newSpannerConnection(connectionString)){// Execute a simple SQL statement.varcmd=connection.CreateSelectCommand(@"SELECT ""Hello World"" as test");using(varreader=awaitcmd.ExecuteReaderAsync()){while(awaitreader.ReadAsync()){Console.WriteLine(reader.GetFieldValue<string>("test"));}}}}publicstaticvoidMain(string[]args){MainAsync().Wait();}}}
Go
// Sample spanner_quickstart is a basic program that uses Cloud Spanner.packagemainimport("context""fmt""log""cloud.google.com/go/spanner""google.golang.org/api/iterator")funcmain(){ctx:=context.Background()// This database must exist.databaseName:="projects/your-project-id/instances/your-instance-id/databases/your-database-id"client,err:=spanner.NewClient(ctx,databaseName)iferr!=nil{log.Fatalf("Failed to create client %v",err)}deferclient.Close()stmt:=spanner.Statement{SQL:"SELECT 1"}iter:=client.Single().Query(ctx,stmt)deferiter.Stop()for{row,err:=iter.Next()iferr==iterator.Done{fmt.Println("Done")return}iferr!=nil{log.Fatalf("Query failed with %v",err)}variint64ifrow.Columns(&i)!=nil{log.Fatalf("Failed to parse row %v",err)}fmt.Printf("Got value %v\n",i)}}
Java
// Imports the Google Cloud client libraryimportcom.google.cloud.spanner.DatabaseClient;importcom.google.cloud.spanner.DatabaseId;importcom.google.cloud.spanner.ResultSet;importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.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. */publicclassQuickstartSample{publicstaticvoidmain(String...args)throwsException{if(args.length!=2){System.err.println("Usage: QuickStartSample <instance_id> <database_id>");return;}// Instantiates a clientSpannerOptionsoptions=SpannerOptions.newBuilder().build();Spannerspanner=options.getService();// Name of your instance & database.StringinstanceId=args[0];StringdatabaseId=args[1];try{// Creates a database clientDatabaseClientdbClient=spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(),instanceId,databaseId));// Queries the databaseResultSetresultSet=dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));System.out.println("\n\nResults:");// Prints the resultswhile(resultSet.next()){System.out.printf("%d\n\n",resultSet.getLong(0));}}finally{// Closes the client which will free up the resources usedspanner.close();}}}
Node.js
// Imports the Google Cloud client libraryconst{Spanner}=require('@google-cloud/spanner');// Creates a clientconstspanner=newSpanner({projectId});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);// The query to executeconstquery={sql:'SELECT 1',};// Execute a simple SQL statementconst[rows]=awaitdatabase.run(query);console.log(`Query: ${rows.length} found.`);rows.forEach(row=>console.log(row));
PHP
# Includes the autoloader for libraries installed with composerrequire __DIR__ . '/vendor/autoload.php';# Imports the Google Cloud client libraryuse Google\Cloud\Spanner\SpannerClient;# Your Google Cloud Platform project ID$projectId = 'YOUR_PROJECT_ID';# Instantiates a client$spanner = new SpannerClient([ 'projectId' => $projectId]);# Your Cloud Spanner instance ID.$instanceId = 'your-instance-id';# Get a Cloud Spanner instance by ID.$instance = $spanner->instance($instanceId);# Your Cloud Spanner database ID.$databaseId = 'your-database-id';# Get a Cloud Spanner database by ID.$database = $instance->database($databaseId);# Execute a simple SQL statement.$results = $database->execute('SELECT "Hello World" as test');foreach ($results as $row) { print($row['test'] . PHP_EOL);}
Python
# Imports the Google Cloud Client Library.fromgoogle.cloudimportspanner# Your Cloud Spanner instance ID.# instance_id = "my-instance-id"## Your Cloud Spanner database ID.# database_id = "my-database-id"# Instantiate a client.spanner_client=spanner.Client()# Get a Cloud Spanner instance by ID.instance=spanner_client.instance(instance_id)# Get a Cloud Spanner database by ID.database=instance.database(database_id)# Execute a simple SQL statement.withdatabase.snapshot()assnapshot:results=snapshot.execute_sql("SELECT 1")forrowinresults:print(row)
Ruby
# Imports the Google Cloud client libraryrequire"google/cloud/spanner"# Your Google Cloud Platform project IDproject_id="YOUR_PROJECT_ID"# Instantiates a clientspanner=Google::Cloud::Spanner.newproject:project_id# Your Cloud Spanner instance IDinstance_id="my-instance"# Your Cloud Spanner database IDdatabase_id="my-database"# Gets a reference to a Cloud Spanner instance databasedatabase_client=spanner.clientinstance_id,database_id# Execute a simple SQL statementresults=database_client.execute_query"SELECT 1"results.rows.eachdo|row|putsrowend
Use the client library for administrator operations
The following list contains links to all the administrator operations you can
use in the Spanner client library:
You can use client libraries to setup, modify, and query property graphs in
Spanner Graph. The following list contains links to learn about
and get started with Spanner Graph using client libraries:
In addition to the libraries shown above, a Spring
Data module is available
for Java applications. Spring Data Spanner helps you use Spanner in
any application that's built with the Spring
Framework.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-06-03 UTC."],[],[]]