Επεξεργασία

Κοινή χρήση μέσω


Create a database in Azure Cosmos DB for NoSQL using .NET

APPLIES TO: NoSQL

Databases in Azure Cosmos DB are units of management for one or more containers. Before you can create or manage containers, you must first create a database.

Name a database

In Azure Cosmos DB, a database is analogous to a namespace. When you create a database, the database name forms a segment of the URI used to access the database resource and any child resources.

Here are some quick rules when naming a database:

  • Database names must not be empty.
  • Database names can't be longer than 256 characters.

Once created, the URI for a database is in this format:

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

Tip

For more information on database name limits, see service quotas and limits

Create a database

To create a database, call one of the following methods:

Create a database asynchronously

The following example creates a database asynchronously:

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

The CosmosClient.CreateDatabaseAsync method throws an exception if a database with the same name already exists.

Create a database asynchronously if it doesn't already exist

The following example creates a database asynchronously only if it doesn't already exist on the account:

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

The CosmosClient.CreateDatabaseIfNotExistsAsync method only creates a new database if it doesn't already exist. This method is useful for avoiding errors if you run the same code multiple times.

Parsing the response

In all examples so far, the response from the asynchronous request was cast immediately to the Database type. You may want to parse metadata about the response including headers and the HTTP status code. The true return type for the CosmosClient.CreateDatabaseAsync and CosmosClient.CreateDatabaseIfNotExistsAsync methods is DatabaseResponse.

The following example shows the CosmosClient.CreateDatabaseIfNotExistsAsync method returning a DatabaseResponse. Once returned, you can parse response properties and then eventually get the underlying Database object:

// 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;

Next steps

Now that you've created a database, use the next guide to create containers.