Getting started with Spanner in Python Stay organized with collections Save and categorize content based on your preferences.
Objectives
This tutorial walks you through the following steps using the Spannerclient library for Python:
- Create a Spanner instance and database.
- Write, read, and execute SQL queries on data in the database.
- Update the database schema.
- Update data using a read-write transaction.
- Add a secondary index to the database.
- Use the index to read and execute SQL queries on data.
- Retrieve data using a read-only transaction.
Costs
This tutorial uses Spanner, which is a billable component of theGoogle Cloud. For information on the cost of using Spanner, seePricing.
Before you begin
Complete the steps described inSet up, which cover creating andsetting a default Google Cloud project, enabling billing, enabling theCloud Spanner API, and setting up OAuth 2.0 to get authentication credentials to usethe Cloud Spanner API.
In particular, make sure that you rungcloud authapplication-default loginto set up your local development environment with authenticationcredentials.
Prepare your local Python environment
Follow the instructionsinSetting Up a Python Development Environment.
Clone the sample app repository to your local machine:
gitclonehttps://github.com/googleapis/python-spannerAlternatively, you candownload the sample as a zip file and extract it.
Change to the directory that contains the Spanner sample code:
cdpython-spanner/samples/samplesCreate an isolated Python environment, and install dependencies:
virtualenvenvsourceenv/bin/activatepipinstall-rrequirements.txt
Create an instance
When you first use Spanner, you must create an instance, which is anallocation of resources that are used by Spanner databases. When youcreate an instance, you choose aninstance configuration, which determineswhere your data is stored, and also the number of nodes to use, which determinesthe amount of serving and storage resources in your instance.
SeeCreate an instanceto learn how to create a Spanner instance using any of thefollowing methods. You can name your instancetest-instance to use it withother topics in this document that reference an instance namedtest-instance.
- The Google Cloud CLI
- The Google Cloud console
- A client library (C++, C#, Go, Java, Node.js, PHP, Python, or Ruby)
Look through sample files
The samples repository contains a sample that shows how to use Spannerwith Python.
Take a look through thesnippets.py file, which shows how to useSpanner. The code shows how to create and use a new database. The datauses the example schema shown in theSchema and data model page.Create a database
GoogleSQL
pythonsnippets.pytest-instance--database-idexample-dbcreate_databasePostgreSQL
pythonpg_snippets.pytest-instance--database-idexample-dbcreate_databaseYou should see:
Createddatabaseexample-dboninstancetest-instanceGoogleSQL
defcreate_database(instance_id,database_id):"""Creates a database and tables for sample data."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.CreateDatabaseRequest(parent=database_admin_api.instance_path(spanner_client.project,instance_id),create_statement=f"CREATE DATABASE `{database_id}`",extra_statements=["""CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX), FullName STRING(2048) AS ( ARRAY_TO_STRING([FirstName, LastName], " ") ) STORED ) PRIMARY KEY (SingerId)""","""CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX) ) PRIMARY KEY (SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE""",],)operation=database_admin_api.create_database(request=request)print("Waiting for operation to complete...")database=operation.result(OPERATION_TIMEOUT_SECONDS)print("Created database{} on instance{}".format(database.name,database_admin_api.instance_path(spanner_client.project,instance_id),))PostgreSQL
defcreate_database(instance_id,database_id):"""Creates a PostgreSql database and tables for sample data."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.CreateDatabaseRequest(parent=database_admin_api.instance_path(spanner_client.project,instance_id),create_statement=f'CREATE DATABASE "{database_id}"',database_dialect=DatabaseDialect.POSTGRESQL,)operation=database_admin_api.create_database(request=request)print("Waiting for operation to complete...")database=operation.result(OPERATION_TIMEOUT_SECONDS)create_table_using_ddl(database.name)print("Created database{} on instance{}".format(database_id,instance_id))defcreate_table_using_ddl(database_name):fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()request=spanner_database_admin.UpdateDatabaseDdlRequest(database=database_name,statements=["""CREATE TABLE Singers ( SingerId bigint NOT NULL, FirstName character varying(1024), LastName character varying(1024), SingerInfo bytea, FullName character varying(2048) GENERATED ALWAYS AS (FirstName || ' ' || LastName) STORED, PRIMARY KEY (SingerId) )""","""CREATE TABLE Albums ( SingerId bigint NOT NULL, AlbumId bigint NOT NULL, AlbumTitle character varying(1024), PRIMARY KEY (SingerId, AlbumId) ) INTERLEAVE IN PARENT Singers ON DELETE CASCADE""",],)operation=spanner_client.database_admin_api.update_database_ddl(request)operation.result(OPERATION_TIMEOUT_SECONDS)The next step is to write data to your database.
Create a database client
Before you can do reads or writes, you must create aClient. Youcan think of aClient as a database connection: all of your interactions withSpanner must go through aClient. Typically you create aClient whenyour application starts up, then you re-use thatClient to read, write, andexecute transactions. The following code shows how to create a client.# Imports the Google Cloud Client Library.fromgoogle.cloudimportspanner# Your Cloud Spanner instance ID.# instance_id = "my-instance-id"## Your Cloud Spanner database ID.# database_id = "my-database-id"# Instantiate a client.spanner_client=spanner.Client()# Get a Cloud Spanner instance by ID.instance=spanner_client.instance(instance_id)# Get a Cloud Spanner database by ID.database=instance.database(database_id)# Execute a simple SQL statement.withdatabase.snapshot()assnapshot:results=snapshot.execute_sql("SELECT 1")forrowinresults:print(row)Read more in theClientreference.
Write data with DML
You can insert data using Data Manipulation Language (DML) in a read-writetransaction.
You use theexecute_update() method to execute a DML statement.
# instance_id = "your-spanner-instance"# database_id = "your-spanner-db-id"spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)definsert_singers(transaction):row_ct=transaction.execute_update("INSERT INTO Singers (SingerId, FirstName, LastName) VALUES ""(12, 'Melissa', 'Garcia'), ""(13, 'Russell', 'Morales'), ""(14, 'Jacqueline', 'Long'), ""(15, 'Dylan', 'Shaw')")print("{} record(s) inserted.".format(row_ct))database.run_in_transaction(insert_singers)Run the sample using theinsert_with_dml argument.
pythonsnippets.pytest-instance--database-idexample-dbinsert_with_dmlYou should see:
4record(s)inserted.Write data with mutations
You can also insert data usingmutations.
You write data using aBatchobject. ABatch object is a container for mutation operations. A mutationrepresents a sequence of inserts, updates, and deletes that Spannerapplies atomically to different rows and tables in a Spanner database.
Theinsert()method in theBatch class adds one or more insert mutations to thebatch. All mutations in a single batch are applied atomically.
This code shows how to write the data using mutations:
definsert_data(instance_id,database_id):"""Inserts sample data into the given database. The database and table must already exist and can be created using `create_database`. """spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.batch()asbatch:batch.insert(table="Singers",columns=("SingerId","FirstName","LastName"),values=[(1,"Marc","Richards"),(2,"Catalina","Smith"),(3,"Alice","Trentor"),(4,"Lea","Martin"),(5,"David","Lomond"),],)batch.insert(table="Albums",columns=("SingerId","AlbumId","AlbumTitle"),values=[(1,1,"Total Junk"),(1,2,"Go, Go, Go"),(2,1,"Green"),(2,2,"Forever Hold Your Peace"),(2,3,"Terrified"),],)print("Inserted data.")Run the sample using theinsert_data argument.
pythonsnippets.pytest-instance--database-idexample-dbinsert_dataYou should see:
Inserteddata.Query data using SQL
Spanner supports a SQL interface for reading data, which you canaccess on the command line using the Google Cloud CLI orprogrammatically usingthe Spanner client library for Python.
On the command line
Execute the following SQL statement to read the values of all columns from theAlbums table:
gcloudspannerdatabasesexecute-sqlexample-db--instance=test-instance \--sql='SELECT SingerId, AlbumId, AlbumTitle FROM Albums'The result shows:
SingerIdAlbumIdAlbumTitle11TotalJunk12Go,Go,Go21Green22ForeverHoldYourPeace23TerrifiedUse the Spanner client library for Python
In addition to executing a SQL statement on the command line, you can issue thesame SQL statement programmatically using the Spanner client library forPython.
Use theexecute_sql()method of aSnapshot object torun the SQL query. To get aSnapshot object, call thesnapshot()method of theDatabaseclass in awith statement.
Here's how to issue the query and access the data:
defquery_data(instance_id,database_id):"""Queries sample data from the database using SQL."""spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:results=snapshot.execute_sql("SELECT SingerId, AlbumId, AlbumTitle FROM Albums")forrowinresults:print("SingerId:{}, AlbumId:{}, AlbumTitle:{}".format(*row))Run the sample using thequery_data argument.
pythonsnippets.pytest-instance--database-idexample-dbquery_dataYou should see the following result:
SingerId:2,AlbumId:2,AlbumTitle:ForeverHoldYourPeaceSingerId:1,AlbumId:2,AlbumTitle:Go,Go,GoSingerId:2,AlbumId:1,AlbumTitle:GreenSingerId:2,AlbumId:3,AlbumTitle:TerrifiedSingerId:1,AlbumId:1,AlbumTitle:TotalJunkQuery using a SQL parameter
If your application has a frequently executed query, you can improve its performanceby parameterizing it. The resulting parametric query can be cached and reused, whichreduces compilation costs. For more information, seeUse query parameters to speed up frequently executed queries.
Here is an example of using a parameter in theWHERE clause toquery records containing a specific value forLastName.
# instance_id = "your-spanner-instance"# database_id = "your-spanner-db-id"spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:results=snapshot.execute_sql("SELECT SingerId, FirstName, LastName FROM Singers ""WHERE LastName = @lastName",params={"lastName":"Garcia"},param_types={"lastName":spanner.param_types.STRING},)forrowinresults:print("SingerId:{}, FirstName:{}, LastName:{}".format(*row))Run the sample using the query_data_with_parameter argument.
pythonsnippets.pytest-instance--database-idexample-dbquery_data_with_parameterYou should see the following result:
SingerId:12,FirstName:Melissa,LastName:GarciaRead data using the read API
In addition to Spanner's SQL interface, Spanner also supports aread interface.
Use theread()method of aSnapshotobject to read rows from the database.To get aSnapshot object, call thesnapshot()method of theDatabaseclass in awith statement.Use aKeySetobject to define a collection of keys and key ranges to read.
Here's how to read the data:
defread_data(instance_id,database_id):"""Reads sample data from the database."""spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:keyset=spanner.KeySet(all_=True)results=snapshot.read(table="Albums",columns=("SingerId","AlbumId","AlbumTitle"),keyset=keyset)forrowinresults:print("SingerId:{}, AlbumId:{}, AlbumTitle:{}".format(*row))Run the sample using theread_data argument.
pythonsnippets.pytest-instance--database-idexample-dbread_dataYou should see output similar to:
SingerId:1,AlbumId:1,AlbumTitle:TotalJunkSingerId:1,AlbumId:2,AlbumTitle:Go,Go,GoSingerId:2,AlbumId:1,AlbumTitle:GreenSingerId:2,AlbumId:2,AlbumTitle:ForeverHoldYourPeaceSingerId:2,AlbumId:3,AlbumTitle:TerrifiedUpdate the database schema
Assume you need to add a new column calledMarketingBudget to theAlbumstable. Adding a new column to an existing table requires an update to yourdatabase schema. Spanner supports schema updates to a database while thedatabase continues to serve traffic. Schema updates don't require taking thedatabase offline and they don't lock entire tables or columns; you can continuewriting data to the database during the schema update. Read more about supportedschema updates and schema change performance inMake schema updates.
Add a column
You can add a column on the command line using the Google Cloud CLI orprogrammatically usingthe Spanner client library for Python.
On the command line
Use the followingALTER TABLE command toadd the new column to the table:
GoogleSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance \--ddl='ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'PostgreSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance \--ddl='ALTER TABLE Albums ADD COLUMN MarketingBudget BIGINT'You should see:
Schemaupdating...done.Use the Spanner client library for Python
Use theupdate_ddl()method of theDatabaseclass to modify the schema:defadd_column(instance_id,database_id):"""Adds a new column to the Albums table in the example database."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.UpdateDatabaseDdlRequest(database=database_admin_api.database_path(spanner_client.project,instance_id,database_id),statements=["ALTER TABLE Albums ADD COLUMN MarketingBudget INT64",],)operation=database_admin_api.update_database_ddl(request)print("Waiting for operation to complete...")operation.result(OPERATION_TIMEOUT_SECONDS)print("Added the MarketingBudget column.")Run the sample using theadd_column argument.
pythonsnippets.pytest-instance--database-idexample-dbadd_columnYou should see:
AddedtheMarketingBudgetcolumn.Write data to the new column
The following code writes data to the new column. It setsMarketingBudget to100000 for the row keyed byAlbums(1, 1) and to500000 for the row keyedbyAlbums(2, 2).
defupdate_data(instance_id,database_id):"""Updates sample data in the database. This updates the `MarketingBudget` column which must be created before running this sample. You can add the column by running the `add_column` sample or by running this DDL statement against your database: ALTER TABLE Albums ADD COLUMN MarketingBudget INT64 """spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.batch()asbatch:batch.update(table="Albums",columns=("SingerId","AlbumId","MarketingBudget"),values=[(1,1,100000),(2,2,500000)],)print("Updated data.")Run the sample using theupdate_data argument.
pythonsnippets.pytest-instance--database-idexample-dbupdate_dataYou can also execute a SQL query or a read call to fetch the values that youjust wrote.
Here's the code to execute the query:
defquery_data_with_new_column(instance_id,database_id):"""Queries sample data from the database using SQL. This sample uses the `MarketingBudget` column. You can add the column by running the `add_column` sample or by running this DDL statement against your database: ALTER TABLE Albums ADD COLUMN MarketingBudget INT64 """spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:results=snapshot.execute_sql("SELECT SingerId, AlbumId, MarketingBudget FROM Albums")forrowinresults:print("SingerId:{}, AlbumId:{}, MarketingBudget:{}".format(*row))To execute this query, run the sample using thequery_data_with_new_column argument.
pythonsnippets.pytest-instance--database-idexample-dbquery_data_with_new_columnYou should see:
SingerId:2,AlbumId:2,MarketingBudget:500000SingerId:1,AlbumId:2,MarketingBudget:NoneSingerId:2,AlbumId:1,MarketingBudget:NoneSingerId:2,AlbumId:3,MarketingBudget:NoneSingerId:1,AlbumId:1,MarketingBudget:100000Update data
You can update data using DML in a read-write transaction.
You use theexecute_update() method to execute a DML statement.
# instance_id = "your-spanner-instance"# database_id = "your-spanner-db-id"spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)deftransfer_budget(transaction):# Transfer marketing budget from one album to another. Performed in a# single transaction to ensure that the transfer is atomic.second_album_result=transaction.execute_sql("SELECT MarketingBudget from Albums ""WHERE SingerId = 2 and AlbumId = 2")second_album_row=list(second_album_result)[0]second_album_budget=second_album_row[0]transfer_amount=200000# Transaction will only be committed if this condition still holds at# the time of commit. Otherwise it will be aborted and the callable# will be rerun by the client libraryifsecond_album_budget >=transfer_amount:first_album_result=transaction.execute_sql("SELECT MarketingBudget from Albums ""WHERE SingerId = 1 and AlbumId = 1")first_album_row=list(first_album_result)[0]first_album_budget=first_album_row[0]second_album_budget-=transfer_amountfirst_album_budget+=transfer_amount# Update first albumtransaction.execute_update("UPDATE Albums ""SET MarketingBudget = @AlbumBudget ""WHERE SingerId = 1 and AlbumId = 1",params={"AlbumBudget":first_album_budget},param_types={"AlbumBudget":spanner.param_types.INT64},)# Update second albumtransaction.execute_update("UPDATE Albums ""SET MarketingBudget = @AlbumBudget ""WHERE SingerId = 2 and AlbumId = 2",params={"AlbumBudget":second_album_budget},param_types={"AlbumBudget":spanner.param_types.INT64},)print("Transferred{} from Album2's budget to Album1's".format(transfer_amount))database.run_in_transaction(transfer_budget)Run the sample using thewrite_with_dml_transaction argument.
pythonsnippets.pytest-instance--database-idexample-dbwrite_with_dml_transactionYou should see:
Transferred200000fromAlbum2's budget to Album1'sUse a secondary index
Suppose you wanted to fetch all rows ofAlbums that haveAlbumTitle valuesin a certain range. You could read all values from theAlbumTitle column usinga SQL statement or a read call, and then discard the rows that don't meet thecriteria, but doing this full table scan is expensive, especially for tableswith a lot of rows. Instead you can speed up the retrieval of rows whensearching by non-primary key columns by creating asecondary index on the table.
Adding a secondary index to an existing table requires a schema update. Likeother schema updates, Spanner supports adding an index while thedatabase continues to serve traffic. Spanner automatically backfills theindex with your existing data. Backfills might take a few minutes to complete,but you don't need to take the database offline or avoid writing to the indexedtable during this process. For more details, seeAdd a secondary index.
After you add a secondary index, Spanner automatically uses it forSQL queries that are likely to run faster with the index. If you use the readinterface, you must specify the index that you want to use.
Add a secondary index
You can add an index on the command line using the gcloud CLI orprogrammatically using the Spanner client library for Python.
On the command line
Use the followingCREATE INDEX commandto add an index to the database:
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance\--ddl='CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'You should see:
Schemaupdating...done.Using the Spanner client library for Python
Use theupdate_ddl()method of theDatabaseclass to add an index:defadd_index(instance_id,database_id):"""Adds a simple index to the example database."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.UpdateDatabaseDdlRequest(database=database_admin_api.database_path(spanner_client.project,instance_id,database_id),statements=["CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"],)operation=database_admin_api.update_database_ddl(request)print("Waiting for operation to complete...")operation.result(OPERATION_TIMEOUT_SECONDS)print("Added the AlbumsByAlbumTitle index.")Run the sample using theadd_index argument.
pythonsnippets.pytest-instance--database-idexample-dbadd_indexAdding an index can take a few minutes. After the index is added, you shouldsee:
AddedtheAlbumsByAlbumTitleindex.Read using the index
For SQL queries, Spanner automatically uses an appropriate index. In theread interface, you must specify the index in your request.
To use the index in the read interface, provide anIndex argument to theread() method of aSnapshotobject. To get aSnapshot object, call thesnapshot() method of theDatabase class in awith statement.
defread_data_with_index(instance_id,database_id):"""Reads sample data from the database using an index. The index must exist before running this sample. You can add the index by running the `add_index` sample or by running this DDL statement against your database: CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle) """spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:keyset=spanner.KeySet(all_=True)results=snapshot.read(table="Albums",columns=("AlbumId","AlbumTitle"),keyset=keyset,index="AlbumsByAlbumTitle",)forrowinresults:print("AlbumId:{}, AlbumTitle:{}".format(*row))Run the sample using theread_data_with_index argument.
pythonsnippets.pytest-instance--database-idexample-dbread_data_with_indexYou should see:
AlbumId:2,AlbumTitle:ForeverHoldYourPeaceAlbumId:2,AlbumTitle:Go,Go,GoAlbumId:1,AlbumTitle:GreenAlbumId:3,AlbumTitle:TerrifiedAlbumId:1,AlbumTitle:TotalJunkAdd an index for index-only reads
You might have noticed that the previous read example doesn't include readingtheMarketingBudget column. This is because Spanner's read interfacedoesn't support the ability to join an index with a data table to look up valuesthat are not stored in the index.
Create an alternate definition ofAlbumsByAlbumTitle that stores a copy ofMarketingBudget in the index.
On the command line
GoogleSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance \--ddl='CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)PostgreSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance \--ddl='CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) INCLUDE (MarketingBudget)Adding an index can take a few minutes. After the index is added, you shouldsee:
Schemaupdating...done.Using the Spanner client library for Python
Use theupdate_ddl()method of theDatabaseclass to add an index with aSTORING clause:defadd_storing_index(instance_id,database_id):"""Adds an storing index to the example database."""fromgoogle.cloud.spanner_admin_database_v1.typesimportspanner_database_adminspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_apirequest=spanner_database_admin.UpdateDatabaseDdlRequest(database=database_admin_api.database_path(spanner_client.project,instance_id,database_id),statements=["CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle)""STORING (MarketingBudget)"],)operation=database_admin_api.update_database_ddl(request)print("Waiting for operation to complete...")operation.result(OPERATION_TIMEOUT_SECONDS)print("Added the AlbumsByAlbumTitle2 index.")Run the sample using theadd_storing_index argument.
pythonsnippets.pytest-instance--database-idexample-dbadd_storing_indexYou should see:
AddedtheAlbumsByAlbumTitle2index.Now you can execute a read that fetches allAlbumId,AlbumTitle, andMarketingBudget columns from theAlbumsByAlbumTitle2 index:
defread_data_with_storing_index(instance_id,database_id):"""Reads sample data from the database using an index with a storing clause. The index must exist before running this sample. You can add the index by running the `add_scoring_index` sample or by running this DDL statement against your database: CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget) """spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot()assnapshot:keyset=spanner.KeySet(all_=True)results=snapshot.read(table="Albums",columns=("AlbumId","AlbumTitle","MarketingBudget"),keyset=keyset,index="AlbumsByAlbumTitle2",)forrowinresults:print("AlbumId:{}, AlbumTitle:{}, ""MarketingBudget:{}".format(*row))Run the sample using theread_data_with_storing_index argument.
pythonsnippets.pytest-instance--database-idexample-dbread_data_with_storing_indexYou should see output similar to:
AlbumId:2,AlbumTitle:ForeverHoldYourPeace,MarketingBudget:300000AlbumId:2,AlbumTitle:Go,Go,Go,MarketingBudget:NoneAlbumId:1,AlbumTitle:Green,MarketingBudget:NoneAlbumId:3,AlbumTitle:Terrified,MarketingBudget:NoneAlbumId:1,AlbumTitle:TotalJunk,MarketingBudget:300000Retrieve data using read-only transactions
Suppose you want to execute more than one read at the same timestamp.Read-onlytransactions observe a consistentprefix of the transaction commit history, so your application always getsconsistent data.Use aSnapshotobject for executing read-only transactions. To get aSnapshot object, call thesnapshot()method of theDatabaseclass in awith statement.
The following shows how to run a query and perform a read in the same read-onlytransaction:
defread_only_transaction(instance_id,database_id):"""Reads data inside of a read-only transaction. Within the read-only transaction, or "snapshot", the application sees consistent view of the database at a particular timestamp. """spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)withdatabase.snapshot(multi_use=True)assnapshot:# Read using SQL.results=snapshot.execute_sql("SELECT SingerId, AlbumId, AlbumTitle FROM Albums")print("Results from first read:")forrowinresults:print("SingerId:{}, AlbumId:{}, AlbumTitle:{}".format(*row))# Perform another read using the `read` method. Even if the data# is updated in-between the reads, the snapshot ensures that both# return the same data.keyset=spanner.KeySet(all_=True)results=snapshot.read(table="Albums",columns=("SingerId","AlbumId","AlbumTitle"),keyset=keyset)print("Results from second read:")forrowinresults:print("SingerId:{}, AlbumId:{}, AlbumTitle:{}".format(*row))Run the sample using theread_only_transaction argument.
pythonsnippets.pytest-instance--database-idexample-dbread_only_transactionYou should see output similar to:
Resultsfromfirstread:SingerId:2,AlbumId:2,AlbumTitle:ForeverHoldYourPeaceSingerId:1,AlbumId:2,AlbumTitle:Go,Go,GoSingerId:2,AlbumId:1,AlbumTitle:GreenSingerId:2,AlbumId:3,AlbumTitle:TerrifiedSingerId:1,AlbumId:1,AlbumTitle:TotalJunkResultsfromsecondread:SingerId:1,AlbumId:1,AlbumTitle:TotalJunkSingerId:1,AlbumId:2,AlbumTitle:Go,Go,GoSingerId:2,AlbumId:1,AlbumTitle:GreenSingerId:2,AlbumId:2,AlbumTitle:ForeverHoldYourPeaceSingerId:2,AlbumId:3,AlbumTitle:TerrifiedCleanup
To avoid incurring additional charges to your Cloud Billing account for theresources used in this tutorial, drop the database and delete the instance thatyou created.
Delete the database
If you delete an instance, all databases within it are automatically deleted.This step shows how to delete a database without deleting an instance (you wouldstill incur charges for the instance).
On the command line
gcloudspannerdatabasesdeleteexample-db--instance=test-instanceUsing the Google Cloud console
Go to theSpanner Instances page in the Google Cloud console.
Click the instance.
Click the database that you want to delete.
In theDatabase details page, clickDelete.
Confirm that you want to delete the database and clickDelete.
Delete the instance
Deleting an instance automatically drops all databases created in that instance.
On the command line
gcloudspannerinstancesdeletetest-instanceUsing the Google Cloud console
Go to theSpanner Instances page in the Google Cloud console.
Click your instance.
ClickDelete.
Confirm that you want to delete the instance and clickDelete.
What's next
Learn how toaccess Spanner with a virtual machine instance.
Learn about authorization and authentication credentials inAuthenticate toCloud services using client libraries.
Learn more about SpannerSchema design best practices.
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-12-17 UTC.