本頁說明如何使用 gcloud
指令列工具插入、更新及刪除資料。
使用 DML 修改資料
如要執行資料操縱語言 (DML) 陳述式,請使用 gcloud spanner databases execute-sql
指令。以下範例會將資料列新增到 Singers
資料表。
gcloud spanner databases execute-sql example-db --instance=test-instance \ --sql="INSERT Singers (SingerId, FirstName, LastName) VALUES (1, 'Marc', 'Richards')"
如要執行分區 DML 陳述式,請使用具備 --enable-partitioned-dml
選項的 gcloud spanner databases execute-sql
指令。以下範例會更新 Albums
資料表中的資料列。
gcloud spanner databases execute-sql example-db \ --instance=test-instance --enable-partitioned-dml \ --sql='UPDATE Albums SET MarketingBudget = 0 WHERE MarketingBudget IS NULL'
如需 Spanner DML 的參考資料,請參閱資料操縱語言語法。
使用資料列指令群組修改資料列
使用 gcloud spanner rows
指令群組修改資料庫中的資料:
- 在資料表中插入新資料列。
- 更新資料表中現有資料列的資料欄。
- 從資料表刪除資料列。
rows
指令群組會認出所有有效資料欄類型的文字值。
在資料表中插入資料列
若要在資料表中插入新資料列,您必須在索引鍵資料欄與任何必填的資料欄中輸入值:
gcloud spanner rows insert --instance=INSTANCE_ID --database=DATABASE_ID \ --table=TABLE_NAME \ --data=COL_NAME_1=COL_VALUE_1,COL_NAME_2=COL_VALUE_2,COL_NAME_3=COL_VALUE_3,...,COL_NAME_N=COL_VALUE_N
以下範例會在 Singers
資料表中插入新資料列:
gcloud spanner rows insert --instance=test-instance --database=example-db \ --table=Singers \ --data=SingerId=1,FirstName='Marc',LastName='Richards'
更新資料表中的資料列
若要在資料表中更新資料列,您必須在索引鍵資料欄與您要更新的資料欄中輸入值:
gcloud spanner rows update --instance=INSTANCE_ID --database=DATABASE_ID \ --table=TABLE_NAME \ --data=COL_NAME_1=COL_VALUE_1,COL_NAME_2=COL_VALUE_2,COL_NAME_3=COL_VALUE_3,...,COL_NAME_N=COL_VALUE_N
以下範例會更新 Singers
資料表中的資料列:
gcloud spanner rows update --instance=test-instance --database=example-db \ --table=Singers \ --data=SingerId=1,FirstName='Marc',LastName='Richards'
您無法使用 update
指令變更鍵值。您必須先建立新資料列,並刪除現有資料列,才可更新鍵值。
從資料表刪除資料列
若要刪除資料列,您必須指定主鍵資料欄的值:
gcloud spanner rows delete --instance=INSTANCE_ID --database=DATABASE_ID \ --table=TABLE_NAME \ --keys=KEY_VALUE_1,KEY_VALUE_2,KEY_VALUE_3
gcloud spanner rows delete --instance=test-instance --database=example-db \ --table=Singers \ --keys=1
指定 ARRAY 值
如要在 ARRAY
欄中插入或更新值,請將資料放入 YAML 檔案,然後使用 --flags-file
選項。
舉例來說,此 YAML 檔案會為 Numbers
資料欄指定陣列 [1,2,3]
:
# stats.yaml
--data:
Id: 1
Locked: True
Numbers:
- 1
- 2
- 3
如要插入含有 YAML 資料的資料列,請使用 --flags-file
選項:
gcloud spanner rows insert --instance=test-instance --database=example-db \ --table=Stats \ --flags-file stats.yaml
如果是 NULL
陣列,請勿在檔案中包含 Numbers
的值:
# stats.yaml
--data:
Id: 1
Locked: True
如果是空陣列,請將陣列定義為 []
:
# stats.yaml
--data:
Id: 1
Locked: True
Numbers: []
指定修訂時間戳記
如要在修訂時間戳記資料欄中自動插入或更新值,請傳入 spanner.commit_timestamp()
做為資料欄的值。以下範例會在插入資料列時,在 LastUpdated
資料欄中寫入認可時間戳記。
gcloud spanner rows insert --instance=test-instance --database=example-db \ --table=Singers \ --data=SingerId=1,LastUpdated='spanner.commit_timestamp()'
以下範例會在 LastUpdated
資料欄中寫入特定的時間戳記值:
gcloud spanner rows update --instance=test-instance --database=example-db \ --table=Singers \ --data=SingerId=1,LastUpdated=2017-01-02T12:34:00.45Z