C# hello world
這個程式碼範例是以 C# 撰寫的「Hello World」應用程式,示範如何完成下列工作:
- 設定驗證方法
- 連線至 Bigtable 執行個體
- 建立新的資料表。
- 將資料寫入資料表。
- 讀取資料。
- 刪除資料表。
設定驗證方法
如要在本機開發環境中使用本頁的 .NET 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
詳情請參閱 Set up authentication for a local development environment。
執行範例
這個程式碼使用 .NET 適用的 Google Cloud 用戶端程式庫中的 C# Admin API 和 C# Data API 程式庫與 Bigtable 進行通訊。
如要執行這個程式範例,請按照 GitHub 上的 .NET Bigtable 範例操作說明進行。完成「建構及執行」和「快速入門」步驟,建立可用於 Hello World 應用程式的資源。請務必編輯 HelloWorld.cs
檔案,新增您建立的資源名稱。
搭配 Bigtable 使用 Cloud 用戶端程式庫
這個應用程式範例會連線至 Bigtable,示範部分簡易作業。
連線至 Bigtable
如要開始使用,請建立可用來連線至 Bigtable 的兩個用戶端物件。C# Admin API BigtableTableAdminClient
可協助您建立及刪除執行個體和資料表。C# Data API BigtableClient
可協助您讀取及寫入資料表資料。
建立資料表
在 BigtableTableAdminClient
類別中呼叫 CreateTable()
方法,產生儲存「hello world」問候語的 Table
物件。資料表有單一資料欄系列,會保留每個值的一個版本。
將資料列寫入資料表
使用包含三個簡單問候語的字串陣列 s_greetings[]
,做為寫入資料表的資料來源。首先,使用 MutateRow()
將單一資料列寫入資料表。接著,循環處理陣列其餘部分,建構每個問候語包含一個項目的 MutateRowsRequest
物件。使用 MutateRows()
提出一次寫入所有項目的要求。接著,循環處理傳回的回應,檢查每個項目的狀態碼,確認是否已成功寫入。
建立篩選器
讀取已寫入的資料前,請先建立篩選器,藉此限制 Bigtable 傳回的資料。即使資料表中含有符合垃圾收集條件但尚未刪除的較舊儲存格,篩選器仍能指示 Bigtable 僅傳回每個值的最新版本。
依資料列索引鍵讀取資料列
使用 ReadRow()
方法傳入您剛建立的篩選器,取得該資料列中每個值的一個版本。
掃描所有資料表資料列
呼叫 ReadRows()
方法並傳入篩選器,即可取得資料表中的所有資料列。您已傳入篩選器,因此 Bigtable 只會傳回每個值的一個版本。
刪除資料表
使用 DeleteTable()
方法刪除資料表。
全面整合使用
以下是不含評論的完整程式碼範例。