- 3.55.0 (latest)
- 3.54.0
- 3.53.0
- 3.52.0
- 3.51.0
- 3.50.1
- 3.46.0
- 3.45.0
- 3.44.0
- 3.43.0
- 3.42.0
- 3.41.0
- 3.40.1
- 3.39.0
- 3.38.0
- 3.37.0
- 3.36.0
- 3.35.1
- 3.34.0
- 3.33.0
- 3.32.0
- 3.31.0
- 3.30.0
- 3.29.0
- 3.28.0
- 3.27.1
- 3.26.0
- 3.25.0
- 3.24.0
- 3.23.0
- 3.22.2
- 3.21.0
- 3.20.0
- 3.19.0
- 3.18.0
- 3.17.0
- 3.16.0
- 3.15.1
- 3.14.1
- 3.13.0
- 3.12.1
- 3.11.1
- 3.10.0
- 3.9.0
- 3.8.0
- 3.7.0
- 3.6.0
- 3.5.0
- 3.4.0
- 3.3.0
- 3.2.0
- 3.1.0
- 3.0.0
- 2.1.1
- 2.0.0
- 1.19.3
- 1.18.0
- 1.17.1
- 1.16.0
- 1.15.1
- 1.14.0
- 1.13.0
- 1.12.0
- 1.11.0
- 1.10.0
Python Client for Cloud Spanner
Cloud Spanner is the world’s first fully managed relational database serviceto offer both strong consistency and horizontal scalability formission-critical online transaction processing (OLTP) applications. With CloudSpanner you enjoy all the traditional benefits of a relational database; butunlike any other relational database service, Cloud Spanner scales horizontallyto hundreds or thousands of servers to handle the biggest transactionalworkloads.
Quick Start
In order to use this library, you first need to go through the following steps:
Installation
Install this library in avirtualenv using pip.virtualenv is a tool tocreate isolated Python environments. The basic problem it addresses is one ofdependencies and versions, and indirectly permissions.
Withvirtualenv, it’s possible to install this library without needing systeminstall permissions, and without clashing with the installed systemdependencies.
Supported Python Versions
Python >= 3.7
Deprecated Python Versions
Python == 2.7.Python == 3.5.Python == 3.6.
Mac/Linux
pip install virtualenvvirtualenv <your-env>source <your-env>/bin/activate<your-env>/bin/pip install google-cloud-spanner
Windows
pip install virtualenvvirtualenv <your-env><your-env>\Scripts\activate<your-env>\Scripts\pip.exe install google-cloud-spanner
Example Usage
Executing Arbitrary SQL in a Transaction
Generally, to work with Cloud Spanner, you will want a transaction. Thepreferred mechanism for this is to create a single function, which executesas a callback todatabase.run_in_transaction
:
# First, define the function that represents a single "unit of work"# that should be run within the transaction.def update_anniversary(transaction, person_id, unix_timestamp): # The query itself is just a string. # # The use of @parameters is recommended rather than doing your # own string interpolation; this provides protections against # SQL injection attacks. query = """SELECT anniversary FROM people WHERE id = @person_id""" # When executing the SQL statement, the query and parameters are sent # as separate arguments. When using parameters, you must specify # both the parameters themselves and their types. row = transaction.execute_sql( query=query, params={'person_id': person_id}, param_types={ 'person_id': types.INT64_PARAM_TYPE, }, ).one() # Now perform an update on the data. old_anniversary = row[0] new_anniversary = _compute_anniversary(old_anniversary, years) transaction.update( 'people', ['person_id', 'anniversary'], [person_id, new_anniversary], )# Actually run the `update_anniversary` function in a transaction.database.run_in_transaction(update_anniversary, person_id=42, unix_timestamp=1335020400,)
Select records using a Transaction
Once you have a transaction object (such as the first argument sent torun_in_transaction
), reading data is easy:
# Define a SELECT query.query = """SELECT e.first_name, e.last_name, p.telephone FROM employees as e, phones as p WHERE p.employee_id == e.employee_id"""# Execute the query and return results.result = transaction.execute_sql(query)for row in result.rows: print(row)
Insert records using Data Manipulation Language (DML) with a Transaction
Use theexecute_update()
method to execute a DML statement:
spanner_client = spanner.Client()instance = spanner_client.instance(instance_id)database = instance.database(database_id)def insert_singers(transaction): row_ct = transaction.execute_update( "INSERT Singers (SingerId, FirstName, LastName) " " VALUES (10, 'Virginia', 'Watson')" ) print("{} record(s) inserted.".format(row_ct))database.run_in_transaction(insert_singers)
Insert records using Mutations with a Transaction
To add one or more records to a table, useinsert
:
transaction.insert( 'citizens', columns=['email', 'first_name', 'last_name', 'age'], values=[ ['phred@exammple.com', 'Phred', 'Phlyntstone', 32], ['bharney@example.com', 'Bharney', 'Rhubble', 31], ],)
Update records using Data Manipulation Language (DML) with a Transaction
spanner_client = spanner.Client()instance = spanner_client.instance(instance_id)database = instance.database(database_id)def update_albums(transaction): row_ct = transaction.execute_update( "UPDATE Albums " "SET MarketingBudget = MarketingBudget * 2 " "WHERE SingerId = 1 and AlbumId = 1" ) print("{} record(s) updated.".format(row_ct))database.run_in_transaction(update_albums)
Update records using Mutations with a Transaction
Transaction.update
updates one or more existing records in a table. Failsif any of the records does not already exist.
transaction.update( 'citizens', columns=['email', 'age'], values=[ ['phred@exammple.com', 33], ['bharney@example.com', 32], ],)
Connection API
Connection API represents a wrap-around for Python Spanner API, written in accordance with PEP-249, and provides a simple way of communication with a Spanner database through connection objects:
from google.cloud.spanner_dbapi.connection import connectconnection = connect("instance-id", "database-id")connection.autocommit = Truecursor = connection.cursor()cursor.execute("SELECT * FROM table_name")result = cursor.fetchall()
If usingfine-grained access controls you can pass adatabase_role
argument to connect as that role:
connection = connect("instance-id", "database-id", database_role='your-role')
Aborted Transactions Retry Mechanism
In!autocommit
mode, transactions can be aborted due to transient errors. In most cases retry of an aborted transaction solves the problem. To simplify it, connection tracks SQL statements, executed in the current transaction. In case the transaction aborted, the connection initiates a new one and re-executes all the statements. In the process, the connection checks that retried statements are returning the same results that the original statements did. If results are different, the transaction is dropped, as the underlying data changed, and auto retry is impossible.
Auto-retry of aborted transactions is enabled only for!autocommit
mode, as inautocommit
mode transactions are never aborted.
Next Steps
See theClient Library Documentation to learn how to connect to CloudSpanner using this Client Library.
Read theProduct documentation to learnmore about the product and see How-to Guides.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-07-18 UTC.