共用方式為


使用 .NET 在 Azure Cosmos DB for NoSQL 中建立資料庫

適用於:NoSQL

Azure Cosmos DB 中的資料庫是一或多個容器的管理單位。 您必須先建立資料庫,才能建立或管理容器。

命名資料庫

在 Azure Cosmos DB 中,資料庫類似於命名空間。 當您建立資料庫時,資料庫名稱會成為存取資料庫資源和任何子資源的 URI 區段。

以下是命名資料庫時的一些快速規則:

  • 資料庫名稱不可空白。
  • 資料庫名稱長度不可超過 256 個字元。

建立之後,資料庫的 URI 格式如下:

https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>

提示

如需資料庫名稱限制的詳細資訊,請參閱服務限額和限制

建立資料庫

若要建立資料庫,請呼叫下列其中一種方法:

以非同步方式建立資料庫

下列範例會以非同步方式建立資料庫:

// New instance of Database class referencing the server-side database
Database database1 = await client.CreateDatabaseAsync(
    id: "adventureworks-1"
);

如果已有同名的資料庫存在,則 CosmosClient.CreateDatabaseAsync 方法會擲回例外狀況。

以非同步方式建立資料庫 (如果不存在)

下列範例只會在帳戶上還沒有資料庫時,以非同步方式建立資料庫:

// New instance of Database class referencing the server-side database
Database database2 = await client.CreateDatabaseIfNotExistsAsync(
    id: "adventureworks-2"
);

CosmosClient.CreateDatabaseIfNotExistsAsync 方法只會在沒有資料庫時建立新的資料庫。 這個方法有助於避免多次執行相同程式碼的錯誤。

剖析回應

在目前為止的所有範例中,非同步要求的回應會立即轉換成 Database 類型。 您可能想要剖析回應的相關中繼資料,包括標頭和 HTTP 狀態碼。 CosmosClient.CreateDatabaseAsyncCosmosClient.CreateDatabaseIfNotExistsAsync 方法的 true 傳回型別為 DatabaseResponse

下列範例顯示 CosmosClient.CreateDatabaseIfNotExistsAsync 方法傳回 DatabaseResponse。 傳回之後,您可以剖析回應屬性,最後取得基礎 Database 物件:

// New instance of Database response class referencing the server-side database
DatabaseResponse response = await client.CreateDatabaseIfNotExistsAsync(
    id: "adventureworks-3"
);
// Parse additional response properties
Database database3 = response.Database;

下一步

現在您已建立了資料庫,請使用下一個指南來建立容器。