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++

See the GitHub quickstart documents for details about this client library's requirements and install dependencies.

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

For more information, see Setting Up a Go Development Environment.

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

Java

For more information, see Setting Up a Java Development Environment.

Maven을 사용하는 경우 pom.xml 파일에 다음을 추가합니다. BOM에 대한 자세한 내용은 Google Cloud Platform 라이브러리 BOM을 참조하세요.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>20.2.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-spanner</artifactId>
  </dependency>

Gradle을 사용하는 경우 종속 항목에 다음을 추가합니다.

implementation platform('com.google.cloud:libraries-bom:20.2.0')

compile 'com.google.cloud:google-cloud-spanner'

SBT를 사용하는 경우 종속 항목에 다음을 추가합니다.

libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "6.4.0"

IntelliJ 또는 Eclipse를 사용하는 경우 다음 IDE 플러그인을 사용하여 클라이언트 라이브러리를 프로젝트에 추가할 수 있습니다.

이 플러그인은 서비스 계정의 키 관리와 같은 추가 기능을 제공합니다. 자세한 내용은 각 플러그인의 문서를 참조하세요.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/spanner

PHP

For more information, see Using PHP on Google Cloud.

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 other ways to authenticate, see the GCP authentication documentation.

Cloud Console

서비스 계정을 만듭니다.

  1. Cloud Console에서 서비스 계정 만들기 페이지로 이동합니다.

    서비스 계정 만들기로 이동
  2. 프로젝트를 선택합니다.
  3. 서비스 계정 이름 필드에 이름을 입력합니다. Cloud Console은 이 이름을 기반으로 서비스 계정 ID 필드를 채웁니다.

    서비스 계정 설명 필드에 설명을 입력합니다. 예를 들면 Service account for quickstart입니다.

  4. 만들기를 클릭합니다.
  5. 역할 선택 필드를 클릭합니다.

    빠른 액세스에서 기본을 클릭한 후 소유자를 클릭합니다.

  6. 계속을 클릭합니다.
  7. 완료를 클릭하여 서비스 계정 만들기를 마칩니다.

    브라우저 창을 닫지 마세요. 다음 단계에서 사용합니다.

서비스 계정 키 만들기

  1. Cloud Console에서 만든 서비스 계정의 이메일 주소를 클릭합니다.
  2. 를 클릭합니다.
  3. 키 추가를 클릭한 후 새 키 만들기를 클릭합니다.
  4. 만들기를 클릭합니다. JSON 키 파일이 컴퓨터에 다운로드됩니다.
  5. 닫기를 클릭합니다.

명령줄

로컬 머신 또는 Cloud Shell에서 Cloud SDK를 사용하여 다음 명령어를 실행할 수 있습니다.

  1. 서비스 계정을 만듭니다. NAME을 서비스 계정 이름으로 바꿉니다.

    gcloud iam service-accounts create NAME
  2. 서비스 계정에 권한을 부여합니다. PROJECT_ID를 프로젝트 ID로 바꿉니다.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. 키 파일을 생성합니다. FILE_NAME을 키 파일 이름으로 바꿉니다.

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

GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정하여 애플리케이션 코드에 사용자 인증 정보를 제공합니다. 이 변수는 현재 셸 세션에만 적용되므로 새 세션을 연 경우 변수를 다시 설정합니다.

Linux 또는 macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH를 서비스 계정 키가 포함된 JSON 파일의 경로로 바꿉니다.

예를 들면 다음과 같습니다.

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH를 서비스 계정 키가 포함된 JSON 파일의 경로로 바꿉니다.

예를 들면 다음과 같습니다.

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

명령어 프롬프트:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

KEY_PATH를 서비스 계정 키가 포함된 JSON 파일의 경로로 바꿉니다.

Using the client library

The following example shows how to use the client library.

C++

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

#include "google/cloud/spanner/client.h"
void Quickstart(std::string const& project_id, std::string const& instance_id,
                std::string const& database_id) {
  namespace spanner = ::google::cloud::spanner;

  auto database = spanner::Database(project_id, instance_id, database_id);
  auto connection = spanner::MakeConnection(database);
  auto client = spanner::Client(connection);

  auto rows =
      client.ExecuteQuery(spanner::SqlStatement("SELECT 'Hello World'"));

  using RowType = std::tuple<std::string>;
  for (auto const& row : spanner::StreamOf<RowType>(rows)) {
    if (!row) throw std::runtime_error(row.status().message());
    std::cout << std::get<0>(*row) << "\n";
  }
}

C#

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.


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

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.


// 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

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

// 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

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

// 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

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

# 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

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

# 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

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

# 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.