Create a database and query a row
Create a schema, insert a row, and query it; Spanner combines relational SQL with transactional consistency.
Apply DDL, insert a fixture, query through the native SDK, and remove owned resources.
SDK dependencies
Run in a new example directory
python3 -m venv .venv
source .venv/bin/activate
python -m pip install google-cloud-spanner Save as hello.py
import os
from uuid import uuid4
from google.cloud import spanner
assert os.environ['SPANNER_EMULATOR_HOST']
client = spanner.Client(project=os.environ['GOOGLE_CLOUD_PROJECT'])
instance = client.instance('guide-' + uuid4().hex[:12], configuration_name='projects/' + client.project + '/instanceConfigs/emulator-config', display_name='Guide', node_count=1)
instance.create().result(timeout=60)
try:
database = instance.database('messages', ddl_statements=['CREATE TABLE Messages (Id INT64 NOT NULL, Message STRING(100)) PRIMARY KEY (Id)'])
database.create().result(timeout=60)
with database.batch() as batch:
batch.insert('Messages', columns=('Id', 'Message'), values=[(1, 'hello')])
with database.snapshot() as snapshot:
rows = list(snapshot.execute_sql('SELECT Message FROM Messages WHERE Id = 1'))
assert rows == [['hello']]
print(rows[0][0])
database.drop()
finally:
instance.delete()
client.close() Run the example
python hello.py Verify the result
The command completes successfully and prints the expected output shown below.
Expected output
hello