|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Use of this source code is governed by a BSD-style |
| 4 | +# license that can be found in the LICENSE file or at |
| 5 | +# https://developers.google.com/open-source/licenses/bsd |
| 6 | + |
| 7 | +import argparse |
| 8 | + |
| 9 | +from google.cloud.spanner_dbapi import connect |
| 10 | + |
| 11 | + |
| 12 | +def enable_autocommit_mode(instance_id, database_id): |
| 13 | + """Enables autocommit mode.""" |
| 14 | + # [START spanner_enable_autocommit_mode] |
| 15 | + |
| 16 | + connection = connect(instance_id, database_id) |
| 17 | + connection.autocommit = True |
| 18 | + print("Autocommit mode is enabled.") |
| 19 | + |
| 20 | + cursor = connection.cursor() |
| 21 | + |
| 22 | + cursor.execute( |
| 23 | + """CREATE TABLE Singers ( |
| 24 | + SingerId INT64 NOT NULL, |
| 25 | + FirstName STRING(1024), |
| 26 | + LastName STRING(1024), |
| 27 | + SingerInfo BYTES(MAX) |
| 28 | + ) PRIMARY KEY (SingerId)""" |
| 29 | + ) |
| 30 | + |
| 31 | + cursor.execute( |
| 32 | + """INSERT INTO Singers (SingerId, FirstName, LastName) VALUES |
| 33 | + (12, 'Melissa', 'Garcia'), |
| 34 | + (13, 'Russell', 'Morales'), |
| 35 | + (14, 'Jacqueline', 'Long'), |
| 36 | + (15, 'Dylan', 'Shaw')""" |
| 37 | + ) |
| 38 | + |
| 39 | + cursor.execute("""SELECT * FROM Singers WHERE SingerId = 13""") |
| 40 | + |
| 41 | + print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*cursor.fetchone())) |
| 42 | + |
| 43 | + connection.close() |
| 44 | + # [END spanner_enable_autocommit_mode] |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + parser = argparse.ArgumentParser( |
| 49 | + description=__doc__, |
| 50 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 51 | + ) |
| 52 | + parser.add_argument("instance_id", help="Your Cloud Spanner instance ID.") |
| 53 | + parser.add_argument( |
| 54 | + "--database-id", |
| 55 | + help="Your Cloud Spanner database ID.", |
| 56 | + default="example_db", |
| 57 | + ) |
| 58 | + subparsers = parser.add_subparsers(dest="command") |
| 59 | + subparsers.add_parser("enable_autocommit_mode", help=enable_autocommit_mode.__doc__) |
| 60 | + args = parser.parse_args() |
| 61 | + if args.command == "enable_autocommit_mode": |
| 62 | + enable_autocommit_mode(args.instance_id, args.database_id) |
| 63 | + else: |
| 64 | + print(f"Command {args.command} did not match expected commands.") |
0 commit comments