[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-05 (世界標準時間)。"],[],[],null,["# Create and query a database using the Google Cloud CLI\n\nObjectives\n----------\n\nThis tutorial walks you through the following steps using the\n[gcloud CLI](/sdk):\n\n- Create a Spanner instance, database, and schema\n- Write data to the database and execute SQL queries that data\n- Clean up by deleting the database and instance\n\nThe procedures on this page apply to both GoogleSQL-dialect databases and PostgreSQL-dialect databases.\n\nFor the complete Spanner `gcloud` reference, see\n[gcloud](/sdk/gcloud/reference/spanner).\n| **Note:** To explore Spanner using a 90-day free trial instance, see [Create a Spanner free trial instance](/spanner/docs/free-trial-quickstart).\n\nPricing\n-------\n\nThis tutorial uses Spanner, which is a billable component of\nGoogle Cloud. For information on the cost of using Spanner, see\n[Pricing](/spanner/pricing).\n\nBefore you begin\n----------------\n\nComplete the steps described in [Install the gcloud CLI and set up\nthe Cloud Spanner API](/spanner/docs/getting-started/set-up), which covers creating\nand setting a default Google Cloud project, enabling billing, enabling the\nCloud Spanner API, and setting up OAuth 2.0 to get authentication credentials to use\nthe Cloud Spanner API.\n\nIn particular, ensure that you run [`gcloud auth application-default\nlogin`](/sdk/gcloud/reference/auth/application-default/login) to set up your\nlocal development environment with authentication credentials.\n\nSet a default project\n---------------------\n\nIf you haven't already done so, set the ID of a Google Cloud project as the default\nproject for the Google Cloud CLI: \n\n```bash\ngcloud config set project PROJECT_ID\n```\n\nIf you don't set the default project, you must pass `--project\nPROJECT_ID` to each of the commands below as the first argument to\n`gcloud`. For example: \n\n```bash\ngcloud --project=PROJECT_ID spanner instance-configs list\n```\n\nInstances\n---------\n\nWhen you first use Spanner, you must create an instance, which is\nan allocation of resources that are used by Spanner databases.\nWhen you create an instance, you choose where your data is stored and how much\n[compute capacity](/spanner/docs/compute-capacity) the instance has.\n\nInstances and instance configurations\n-------------------------------------\n\nTo create an instance, you must select an instance\nconfiguration, which is like a blueprint for your instance that defines the\ngeographic placement and replication of your Spanner data.\n\n### List instance configurations\n\nWhen you create an instance, you specify an *instance configuration* , which\ndefines the geographic placement and replication of your databases in that\ninstance. You can choose a regional configuration, which stores data in one\nregion, a dual-region, which stores data in two regions in the same country, or\na multi-region configuration, which distributes data across multiple\nregions. For more information, see the [Instances overview](/spanner/docs/instances).\n\nTo see the set of instance configurations that are available for your project: \n\n```bash\ngcloud spanner instance-configs list\n```\n\nYou should see a list of regional, dual-region, and multi-region configurations.\n\n### Create an instance\n\nTo create an instance named `test-instance` with the display name `My Instance`\nusing the regional instance configuration `regional-us-central1` with 1 nodes: \n\n```bash\ngcloud spanner instances create test-instance --config=regional-us-central1 \\\n --description=\"My Instance\" --nodes=1\n```\n\nIn the command above, the instance name is set to `test-instance` and\n`--description` sets the display name of the instance. Both of these values\nmust be unique within a Google Cloud Platform project.\n| **Note:** Use the instance ID, not the display name, when referring to an instance in `gcloud` commands.\n\n### Set the default instance\n\nYou can set the default instance that Spanner uses when you have not\nspecified an instance in your command. To set the default instance: \n\n```bash\ngcloud config set spanner/instance test-instance\n```\n\nCreate a database\n-----------------\n\nCreate a database named `example-db`. The database dialect defaults to GoogleSQL. \n\n### GoogleSQL\n\n```bash\ngcloud spanner databases create example-db\n```\n\n### PostgreSQL\n\n```bash\ngcloud spanner databases create example-db --database-dialect=POSTGRESQL\n```\n\nUpdate the schema\n-----------------\n\nUse Spanner's [Data Definition Language](/spanner/docs/reference/standard-sql/data-definition-language)\n(DDL) to create, alter, or drop tables, and to create or drop indexes.\n\nLet's create two tables: \n\n### GoogleSQL\n\n```bash\ngcloud spanner databases ddl update example-db \\\n--ddl='CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX) ) PRIMARY KEY (SingerId)'\n\ngcloud spanner databases ddl update example-db \\\n--ddl='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'\n```\n\n### PostgreSQL\n\n```bash\ngcloud spanner databases ddl update example-db \\\n--ddl='CREATE TABLE Singers ( SingerId bigint NOT NULL, FirstName varchar(1024), LastName varchar(1024), SingerInfo bytea, PRIMARY KEY (SingerId) )'\n\ngcloud spanner databases ddl update example-db \\\n--ddl='CREATE TABLE Albums ( SingerId bigint NOT NULL, AlbumId bigint NOT NULL, AlbumTitle varchar, PRIMARY KEY (SingerId, AlbumId) ) INTERLEAVE IN PARENT Singers ON DELETE CASCADE'\n```\n\nTo check the progress of the operation, use\n[`gcloud spanner operations describe`](/sdk/gcloud/reference/spanner/operations/describe).\nThis command requires the operation ID.\n\nGet the operation ID: \n\n```bash\ngcloud spanner operations list --instance=\"test-instance\" \\\n--database=DATABASE-NAME --type=DATABASE_UPDATE_DDL\n```\n\nReplace \u003cvar translate=\"no\"\u003eDATABASE-NAME\u003c/var\u003e with the name of the database.\n\nRun `gcloud spanner operations describe`: \n\n```bash\ngcloud spanner operations describe \\\n --instance=\"test-instance\" \\\n --database=\"example-db\" \\\n projects/PROJECT-NAME/instances/test-instance/databases/example-db/operations/OPERATION-ID\n```\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003ePROJECT-NAME\u003c/var\u003e: The project name.\n- \u003cvar translate=\"no\"\u003eOPERATION-ID\u003c/var\u003e: The operation ID of the operation that you want to check.\n\nThe output looks similar to the following: \n\n```bash\ndone: true\nmetadata:\n...\nprogress:\n- endTime: '2022-03-01T00:28:06.691403Z'\n progressPercent: 100\n startTime: '2022-03-01T00:28:04.221401Z'\n- endTime: '2022-03-01T00:28:17.624588Z'\n startTime: '2022-03-01T00:28:06.691403Z'\n progressPercent: 100\n...\n```\n\nWrite data\n----------\n\nLet's add some sample data to our database \n\n### GoogleSQL\n\n```bash\ngcloud spanner rows insert --database=example-db \\\n --table=Singers \\\n --data=SingerId=1,FirstName=Marc,LastName=Richards\n\ngcloud spanner rows insert --database=example-db \\\n --table=Singers \\\n --data=SingerId=2,FirstName=Catalina,LastName=Smith\n\ngcloud spanner rows insert --database=example-db \\\n --table=Singers \\\n --data=SingerId=3,FirstName=Alice,LastName=Trentor\n\ngcloud spanner rows insert --database=example-db \\\n --table=Albums \\\n --data=SingerId=1,AlbumId=1,AlbumTitle=\"Total Junk\"\n\ngcloud spanner rows insert --database=example-db \\\n --table=Albums \\\n --data=SingerId=2,AlbumId=1,AlbumTitle=\"Green\"\n\ngcloud spanner rows insert --database=example-db \\\n --table=Albums \\\n --data=^:^SingerId=2:AlbumId=2:AlbumTitle=\"Go, Go, Go\"\n```\n\nBy default, a comma is used to delimit items in lists. In the last insert\ncommand, we specified a colon (`^:^`) as the delimiter so that we could use a\ncomma in the album title.\n\n### PostgreSQL\n\n**Note:** There is a known issue where the gcloud CLI can't look up table names when using mutations to write data to a PostgreSQL database. Therefore, you must use DML to insert data. \n\n```bash\ngcloud spanner databases execute-sql example-db \\\n --sql=\"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES (1, 'Marc', 'Richards')\"\n\ngcloud spanner databases execute-sql example-db \\\n --sql=\"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES (2, 'Catalina', 'Smith')\"\n\ngcloud spanner databases execute-sql example-db \\\n --sql=\"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES (3, 'Alice', 'Trentor')\"\n\ngcloud spanner databases execute-sql example-db \\\n --sql=\"INSERT INTO Albums (SingerId, AlbumId, AlbumTitle) VALUES (1, 1, 'Total Junk')\"\n\ngcloud spanner databases execute-sql example-db \\\n --sql=\"INSERT INTO Albums (SingerId, AlbumId, AlbumTitle) VALUES (2, 1, 'Green')\"\n\ngcloud spanner databases execute-sql example-db \\\n --sql=\"INSERT INTO Albums (SingerId, AlbumId, AlbumTitle) VALUES (2, 2, 'Go, Go, Go')\"\n```\n\nQuery data using SQL\n--------------------\n\nExecute a query on the command line: \n\n```bash\ngcloud spanner databases execute-sql example-db \\\n --sql='SELECT SingerId, AlbumId, AlbumTitle FROM Albums'\n```\n\nFor the Spanner SQL reference, see\n[Query syntax for GoogleSQL](/spanner/docs/reference/standard-sql/query-syntax) or\n[Query syntax for PostgreSQL](/spanner/docs/reference/postgresql/query-syntax).\n\nTo see a list of flags you can use with the `execute-sql` command, see\n[gcloud spanner databases execute-sql](/sdk/gcloud/reference/spanner/databases/execute-sql).\n\nCleanup\n-------\n\nTo avoid incurring additional charges to your Google Cloud account for the\nresources used in this tutorial, drop the database and delete the instance that\nyou created.\n\n### Drop a database\n\nTo delete an existing instance: \n\n```bash\ngcloud spanner databases delete example-db\n```\n\n### Delete an instance\n\nTo delete an existing instance: \n\n```bash\ngcloud spanner instances delete test-instance\n```\n\nNote that deleting an instance also drops all of the databases in that instance.\nDeleting an instance is not reversible."]]