이 튜토리얼에서는 청구 가능한Google Cloud구성요소인 Spanner를 사용합니다. Spanner 사용 비용에 대한 자세한 내용은 가격 책정을 참조하세요.
시작하기 전에
기본 Google Cloud 프로젝트 만들기 및 설정, 결제 사용 설정, Cloud Spanner API 사용 설정, OAuth 2.0 설정을 다루는 gcloud CLI 설치 및 Cloud Spanner API 설정에 설명된 단계를 완료하여 Cloud Spanner API를 사용할 사용자 인증 정보를 가져옵니다.
Spanner를 처음 사용하는 경우에는 인스턴스를 만들어야 합니다. 이 인스턴스는 Spanner 데이터베이스에서 사용하는 리소스를 할당한 것입니다.
인스턴스를 만들 때 데이터 저장 위치와 인스턴스의 컴퓨팅 용량을 선택합니다.
인스턴스 및 인스턴스 구성
인스턴스를 만들려면 인스턴스 구성을 선택해야 합니다. 이는 Spanner 데이터의 지리적 위치와 복제를 정의하는 인스턴스의 청사진과 같은 것입니다.
인스턴스 구성 나열
인스턴스를 만들 때 해당 인스턴스에 있는 데이터베이스의 지리적 위치와 복제를 정의하는 인스턴스 구성을 지정합니다. 한 리전에 데이터를 저장하는 리전 구성, 동일한 국가의 두 리전에 데이터를 저장하는 이중 리전 또는 여러 리전에 데이터를 분산하는 멀티 리전 구성을 선택할 수 있습니다. 자세한 내용은 인스턴스 개요를 참조하세요.
프로젝트에 사용할 수 있는 인스턴스 구성 세트를 보려면 다음 명령어를 사용합니다.
gcloudspannerinstance-configslist
리전, 이중 리전, 멀티 리전 구성 목록이 표시됩니다.
인스턴스 만들기
노드가 1개인 리전 인스턴스 구성 regional-us-central1을 사용하여 표시 이름이 My Instance인 test-instance라고 하는 인스턴스를 만들려면 다음을 실행합니다.
[[["이해하기 쉬움","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(UTC)"],[],[],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."]]