Cloud Spanner Client Libraries

This page shows how to get started with the 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 Compute Engine, App Engine flexible environment, Google Kubernetes Engine, and Cloud Functions. The Cloud Spanner client library for Java is 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 Cloud Spanner.

Installing the client library

C#

For more information, see Setting Up a C# Development Environment. To install the Google.Cloud.Spanner.Data client library in Visual Studio, do the following:

  1. Right-click your solution in Visual Studio and select Manage Nuget packages for solution.

  2. Select the Include prerelease checkbox.

  3. Search for and install the package named Google.Cloud.Spanner.Data.

Go

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

Java

For more information, see Setting Up a Java Development Environment. Se você estiver usando o Maven, adicione ao seu arquivo pom.xml:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-spanner</artifactId>
  <version>1.6.0</version>
</dependency>
Se você estiver usando o Gradle, adicione às suas dependências:
compile 'com.google.cloud:google-cloud-spanner:1.6.0'
Se você estiver usando o SBT, adicione às suas dependências:
libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "1.6.0"

Caso você esteja usando o IntelliJ ou o Eclipse, poderá adicionar bibliotecas de cliente ao seu projeto usando estes plug-ins de ambiente de desenvolvimento integrado:

Os plug-ins também oferecem outras funcionalidades, como gerenciamento de chaves de contas de serviço. Consulte a documentação de cada plug-in para mais detalhes.

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/spanner

PHP

composer require google/cloud-spanner

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-spanner

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-spanner

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

Console do GCP

  1. No Console do GCP, acesse a página Criar chave da conta de serviço.

    Acessar a página "Criar chave da conta de serviço"
  2. Na lista Conta de serviço, selecione Nova conta de serviço.
  3. No campo Nome da conta de serviço, insira um nome.
  4. Na lista Papel, selecione Projeto > Proprietário.

    Observação: o campo Papel autoriza sua conta de serviço a acessar recursos. É possível ver e alterar esse campo no Console do GCP posteriormente. Se você estiver desenvolvendo um aplicativo de produção, especifique permissões mais granulares do que Projeto > Proprietário. Para mais informações, consulte Como atribuir papéis a contas de serviço.
  5. Clique em Criar. O download de um arquivo JSON que contém sua chave é feito no seu computador.

Linha de comando

É possível executar os seguintes comandos usando o SDK do Cloud na máquina local ou no Cloud Shell.

  1. Crie a conta de serviço. Substitua [NAME] por um nome para a conta de serviço.

    gcloud iam service-accounts create [NAME]
  2. Conceda permissões à conta de serviço. Substitua [PROJECT-ID] pelo ID do projeto.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Observação: o campo Papel autoriza a conta de serviço a acessar recursos. É possível ver e alterar esse campo no Console do GCP posteriormente. Se você estiver desenvolvendo um aplicativo de produção, especifique permissões mais granulares do que Projeto > Proprietário. Para mais informações, consulte Como atribuir papéis a contas de serviço.
  3. Gere o arquivo de chave. Substitua [FILE_NAME] pelo nome do arquivo de chave.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

Para fornecer credenciais de autenticação ao código do aplicativo, configure a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS. Substitua [PATH] pelo caminho do arquivo JSON que contém a chave da conta de serviço e [FILE_NAME] pelo nome do arquivo. Essa variável só se aplica à sessão de shell atual. Dessa maneira, se você abrir uma nova sessão, precisará definir a variável novamente.

Linux ou macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por exemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

Com o PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por exemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

Com o prompt de comando:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#


using Google.Cloud.Spanner.Data;
using System;
using System.Threading.Tasks;

namespace GoogleCloudSamples.Spanner
{
    public class QuickStart
    {
        static async Task MainAsync()
        {
            string projectId = "YOUR-PROJECT-ID";
            string instanceId = "my-instance";
            string databaseId = "my-database";
            string connectionString =
                $"Data Source=projects/{projectId}/instances/{instanceId}/"
                + $"databases/{databaseId}";
            // Create connection to Cloud Spanner.
            using (var connection = new SpannerConnection(connectionString))
            {
                // Execute a simple SQL statement.
                var cmd = connection.CreateSelectCommand(
                    @"SELECT ""Hello World"" as test");
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        Console.WriteLine(
                            reader.GetFieldValue<string>("test"));
                    }
                }
            }
        }
        public static void Main(string[] args)
        {
            MainAsync().Wait();
        }
    }
}

Go


// Sample spanner_quickstart is a basic program that uses Cloud Spanner.
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/spanner"
	"google.golang.org/api/iterator"
)

func main() {
	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)
	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()

	for {
		row, err := iter.Next()
		if err == iterator.Done {
			fmt.Println("Done")
			return
		}
		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)
	}
}

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.close();
    }
  }
}

Node.js

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

// Creates a client
const spanner = new Spanner({projectId});

// 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
const [rows] = await database.run(query);
console.log(`Query: ${rows.length} found.`);
rows.forEach(row => console.log(row));

PHP

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use 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.
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.
with database.snapshot() as snapshot:
    results = snapshot.execute_sql('SELECT 1')

    for row in results:
        print(row)

Ruby

# Imports the Google Cloud client library
require "google/cloud/spanner"

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Instantiates a client
spanner = Google::Cloud::Spanner.new project: project_id

# Your Cloud Spanner instance ID
instance_id = "my-instance"

# Your Cloud Spanner database ID
database_id = "my-database"

# Gets a reference to a Cloud Spanner instance database
database_client = spanner.client instance_id, database_id

# Execute a simple SQL statement
database_client.transaction do |transaction|
  results = transaction.execute "SELECT 1"

  results.rows.each do |row|
    puts row
  end
end

Additional resources

Additional client libraries

In addition to the libraries shown above, a Spring Data module is available for Java applications. Spring Data Cloud Spanner helps you use Cloud Spanner in any application that's built with the Spring Framework.

To get started, learn how to add Spring Data Cloud Spanner to your application.

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…

Cloud Spanner Documentation