Create client with query options

Create a client with query options. The client can then be used to read, write, and run transactions.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespacespanner=::google::cloud::spanner;
spanner::Clientclient(
spanner::MakeConnection(db),
google::cloud::Options{}
.set<spanner::QueryOptimizerVersionOption>("1")
.set<spanner::QueryOptimizerStatisticsPackageOption>(
"auto_20191128_14_47_22UTC"));

C#

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


usingGoogle.Cloud.Spanner.Data ;
usingSystem.Collections.Generic;
usingSystem.Threading.Tasks;
publicclassCreateConnectionWithQueryOptionsAsyncSample
{
publicclassAlbum
{
publicintAlbumId{get;set;}
publicintSingerId{get;set;}
publicstringAlbumTitle{get;set;}
}
publicasyncTask<List<Album>>CreateConnectionWithQueryOptionsAsync(stringprojectId,stringinstanceId,stringdatabaseId)
{
stringconnectionString=$"Data Source=projects/{projectId}/instances/{instanceId}/databases/{databaseId}";
usingvarconnection=newSpannerConnection (connectionString)
{
// Set query options on the connection.
QueryOptions=QueryOptions .Empty
.WithOptimizerVersion ("1")
// The list of available statistics packages for the database can
// be found by querying the "INFORMATION_SCHEMA.SPANNER_STATISTICS"
// table.
.WithOptimizerStatisticsPackage ("latest")
};
varalbums=newList<Album>();
varcmd=connection.CreateSelectCommand ("SELECT SingerId, AlbumId, AlbumTitle FROM Albums");
usingvarreader=awaitcmd.ExecuteReaderAsync ();
while(awaitreader.ReadAsync ())
{
albums.Add(newAlbum
{
SingerId=reader.GetFieldValue<int>("SingerId"),
AlbumId=reader.GetFieldValue<int>("AlbumId"),
AlbumTitle=reader.GetFieldValue<string>("AlbumTitle")
});
}
returnalbums;
}
}

Go

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import(
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/spanner"
sppb"cloud.google.com/go/spanner/apiv1/spannerpb"
"google.golang.org/api/iterator"
)
funccreateClientWithQueryOptions(wio.Writer,databasestring)error{
ctx:=context.Background()
queryOptions:=spanner.QueryOptions {
Options:&sppb.ExecuteSqlRequest_QueryOptions{
OptimizerVersion:"1",
// The list of available statistics packages can be found by
// querying the "INFORMATION_SCHEMA.SPANNER_STATISTICS" table.
OptimizerStatisticsPackage:"latest",
},
}
client,err:=spanner.NewClientWithConfig (
ctx,database,spanner.ClientConfig {QueryOptions:queryOptions},
)
iferr!=nil{
returnerr
}
deferclient.Close()
stmt:=spanner.Statement {SQL:`SELECT VenueId, VenueName, LastUpdateTime FROM Venues`}
iter:=client.Single ().Query(ctx,stmt)
deferiter.Stop()
for{
row,err:=iter.Next()
iferr==iterator.Done{
returnnil
}
iferr!=nil{
returnerr
}
varvenueIDint64
varvenueNamestring
varlastUpdateTimetime.Time
iferr:=row.Columns (&venueID,&venueName,&lastUpdateTime);err!=nil{
returnerr
}
fmt.Fprintf(w,"%d %s %s\n",venueID,venueName,lastUpdateTime)
}
}

Java

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

staticvoidclientWithQueryOptions(DatabaseIddb){
SpannerOptionsoptions=
SpannerOptions.newBuilder()
.setDefaultQueryOptions(
db,QueryOptions
.newBuilder()
.setOptimizerVersion("1")
// The list of available statistics packages can be found by querying the
// "INFORMATION_SCHEMA.SPANNER_STATISTICS" table.
.setOptimizerStatisticsPackage("latest")
.build())
.build();
Spannerspanner=options.getService();
DatabaseClientdbClient=spanner.getDatabaseClient(db);
try(ResultSetresultSet=
dbClient
.singleUse()
.executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))){
while(resultSet.next()){
System.out.printf(
"%d %d %s\n",resultSet.getLong(0),resultSet.getLong(1),resultSet.getString(2));
}
}
}

Node.js

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Imports the Google Cloud client library
const{Spanner}=require('@google-cloud/spanner');
/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// Creates a client
constspanner=newSpanner ({
projectId:projectId,
});
// Gets a reference to a Cloud Spanner instance and database
constinstance=spanner.instance(instanceId);
constdatabase=instance.database(
databaseId,
{},
{
optimizerVersion:'1',
// The list of available statistics packages can be found by querying the
// "INFORMATION_SCHEMA.SPANNER_STATISTICS" table.
optimizerStatisticsPackage:'latest',
},
);
constquery={
sql:`SELECT AlbumId, AlbumTitle, MarketingBudget
 FROM Albums
 ORDER BY AlbumTitle`,
};
// Queries rows from the Albums table
try{
const[rows]=awaitdatabase.run(query);
rows.forEach(row=>{
constjson=row.toJSON();
constmarketingBudget=json.MarketingBudget
?json.MarketingBudget
:null;// This value is nullable
console.log(
`AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}, MarketingBudget: ${marketingBudget}`,
);
});
}catch(err){
console.error('ERROR:',err);
}finally{
// Close the database when finished.
database.close();
}

PHP

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Spanner\SpannerClient;
use Google\Cloud\Spanner\Database;
/**
 * Create a client with query options.
 * Example:
 * ```
 * create_client_with_query_options($instanceId, $databaseId);
 * ```
 *
 * @param string $instanceId The Spanner instance ID.
 * @param string $databaseId The Spanner database ID.
 */
function create_client_with_query_options(string $instanceId, string $databaseId): void
{
 $spanner = new SpannerClient([
 'queryOptions' => [
 'optimizerVersion' => '1',
 // Pin the statistics package used for this client instance to the
 // latest version. The list of available statistics packages can be
 // found by querying the "INFORMATION_SCHEMA.SPANNER_STATISTICS"
 // table.
 'optimizerStatisticsPackage' => 'latest'
 ]
 ]);
 $instance = $spanner->instance($instanceId);
 $database = $instance->database($databaseId);
 $results = $database->execute(
 'SELECT VenueId, VenueName, LastUpdateTime FROM Venues'
 );
 foreach ($results as $row) {
 printf('VenueId: %s, VenueName: %s, LastUpdateTime: %s' . PHP_EOL,
 $row['VenueId'], $row['VenueName'], $row['LastUpdateTime']);
 }
}

Python

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# instance_id = "your-spanner-instance"
# database_id = "your-spanner-db-id"
spanner_client = spanner.Client(
 query_options={
 "optimizer_version": "1",
 "optimizer_statistics_package": "latest",
 }
)
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
with database.snapshot() as snapshot:
 results = snapshot.execute_sql(
 "SELECT VenueId, VenueName, LastUpdateTime FROM Venues"
 )
 for row in results:
 print("VenueId: {}, VenueName: {}, LastUpdateTime: {}".format(*row))

Ruby

To learn how to install and use the client library for Spanner, see Spanner client libraries.

To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require"google/cloud/spanner"
query_options={
optimizer_version:"1",
# The list of available statistics packages can be
# found by querying the "INFORMATION_SCHEMA.SPANNER_STATISTICS"
# table.
optimizer_statistics_package:"latest"
}
spanner=Google::Cloud::Spanner .newproject:project_id
client=spanner.client instance_id,database_id,query_options:query_options
sql_query="SELECT VenueId, VenueName, LastUpdateTime FROM Venues"
client.execute(sql_query).rows.each do|row|
puts"#{row[:VenueId]}#{row[:VenueName]}#{row[:LastUpdateTime]}"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.