Google Cloud Spanner Client Library

3.63.0 · active · verified Sun Mar 29

The `google-cloud-spanner` client library for Python enables developers to interact with Google Cloud Spanner, a fully managed, horizontally scalable, relational database service. It provides high-level APIs for creating instances and databases, executing SQL queries, managing transactions, and performing schema updates. The library maintains a rapid release cadence, with updates typically occurring on a monthly basis, introducing new features and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Cloud Spanner client, connect to an existing instance and database, and execute a simple SQL query. Ensure you have authenticated your Google Cloud environment (e.g., via `gcloud auth application-default login`) and set the `GOOGLE_CLOUD_PROJECT`, `SPANNER_INSTANCE_ID`, and `SPANNER_DATABASE_ID` environment variables or replace the placeholders.

import os
from google.cloud import spanner

project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')
instance_id = os.environ.get('SPANNER_INSTANCE_ID', 'your-instance-id')
database_id = os.environ.get('SPANNER_DATABASE_ID', 'your-database-id')


def query_data(project_id, instance_id, database_id):
    spanner_client = spanner.Client(project=project_id)
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    with database.snapshot() as snapshot:
        results = snapshot.execute_sql('SELECT 1').fields
        for row in results:
            print(row)

    print(f'Successfully queried data from {database_id} in {instance_id}.')

# Example usage (uncomment to run, ensure environment variables are set or replace placeholders)
# if __name__ == '__main__':
#     query_data(project_id, instance_id, database_id)

view raw JSON →