如何搭配 C++ 使用 Azure 表格儲存體和 Azure Cosmos DB 資料表 APIHow to use Azure Table storage and Azure Cosmos DB Table API with C++

適用於: 資料表 API

提示

本文中的內容適用於 Azure 資料表儲存體和 Azure Cosmos DB 資料表 API。The content in this article applies to Azure Table storage and the Azure Cosmos DB Table API. Azure Cosmos DB 資料表 API 是資料表儲存體的進階供應項目,可提供輸送量最佳化的資料表、全域發佈,以及自動次要索引。The Azure Cosmos DB Table API is a premium offering for table storage that offers throughput-optimized tables, global distribution, and automatic secondary indexes.

本指南會示範使用 Azure 表格儲存體服務或 Azure Cosmos DB 資料表 API 的一般案例。This guide shows you common scenarios by using the Azure Table storage service or Azure Cosmos DB Table API. 這些範例均以 C++ 撰寫,並使用 Azure Storage Client Library for C++The samples are written in C++ and use the Azure Storage Client Library for C++. 本文涵蓋下列案例:This article covers the following scenarios:

  • 建立和刪除資料表Create and delete a table
  • 使用資料表實體Work with table entities

注意

本指南以 Azure Storage Client Library for C++ 1.0.0 版和更新版本為對象。This guide targets the Azure Storage Client Library for C++ version 1.0.0 and above. 建議版本為 Storage Client Library 2.2.0,可透過 NuGetGitHub 取得。The recommended version is Storage Client Library 2.2.0, which is available by using NuGet or GitHub.

建立帳戶Create accounts

建立 Azure 服務帳戶Create an Azure service account

您可以使用 Azure 表格儲存體或 Azure Cosmos DB 來搭配使用表格。You can work with tables using the Azure Table storage or the Azure Cosmos DB. 若要深入了解這兩項服務中的資料表供應項目間的差異,請參閱資料表供應項目一文。To learn more about the differences between table offerings in these two services, see the Table offerings article. 您必須為您要使用的服務建立帳戶。You'll need to create an account for the service you're going to use. 下列各節說明如何建立 Azure 資料表儲存體和 Azure Cosmos DB 帳戶,不過您可以只使用其中一個。The following sections show how to create both Azure Table storage and the Azure Cosmos DB account, however you can just use one of them.

建立 Azure 儲存體帳戶Create an Azure storage account

建立 Azure 儲存體帳戶最簡單的方法,就是使用 Azure 入口網站The easiest way to create an Azure storage account is by using the Azure portal. 若要深入了解,請參閱 建立儲存體帳戶To learn more, see Create a storage account.

您也可以使用 Azure PowerShellAzure CLI 來建立 Azure 儲存體帳戶。You can also create an Azure storage account by using Azure PowerShell or Azure CLI.

如果您不想在此時建立儲存體帳戶,也可以使用 Azure 儲存體模擬器在本機環境中執行並測試您的程式碼。If you prefer not to create a storage account at this time, you can also use the Azure Storage Emulator to run and test your code in a local environment. 如需詳細資訊,請參閱使用 Azure 儲存體模擬器進行開發和測試For more information, see Use the Azure Storage Emulator for development and testing.

建立 Azure Cosmos DB 表格 API 帳戶Create an Azure Cosmos DB Table API account

有關建立 Azure Cosmos DB 資料表 API 帳戶的指示,請參閱建立表格資料庫帳戶For instructions on creating an Azure Cosmos DB Table API account, see Create a database account.

建立 C++ 應用程式Create a C++ application

在本指南中,會使用到 C++ 應用程式的儲存體功能。In this guide, you use storage features from a C++ application. 因此請安裝 Azure Storage Client Library for C++。To do so, install the Azure Storage Client Library for C++.

請透過下列方法安裝 Azure Storage Client Library for C++:To install the Azure Storage Client Library for C++, use the following methods:

.\vcpkg.exe install azure-storage-cpp

您可以在讀我檔案檔案中找到建置原始程式碼及匯出至 Nuget 的指南。You can find a guide for how to build the source code and export to Nuget in the README file.

設定資料表用戶端程式庫的存取權Configure access to the Table client library

若要使用 Azure 儲存體 API 存取資料表,請將下列 include 陳述式新增到 C++ 檔案的頂端:To use the Azure storage APIs to access tables, add the following include statements to the top of the C++ file:

#include <was/storage_account.h>
#include <was/table.h>

Azure 儲存體用戶端或 Cosmos DB 用戶端會使用連接字串來儲存端點與認證,以存取資料管理服務。An Azure Storage client or Cosmos DB client uses a connection string to store endpoints and credentials to access data management services. 執行用戶端應用程式時,您必須提供正確格式的儲存體連接字串或 Azure Cosmos DB 連接字串。When you run a client application, you must provide the storage connection string or Azure Cosmos DB connection string in the appropriate format.

設定 Azure 儲存體連接字串Set up an Azure Storage connection string

本範例會示範如何宣告靜態欄位來存放 Azure 儲存體連接字串:This example shows how to declare a static field to hold the Azure Storage connection string:

// Define the Storage connection string with your values.
const utility::string_t storage_connection_string(U("DefaultEndpointsProtocol=https;AccountName=<your_storage_account>;AccountKey=<your_storage_account_key>"));

對於 <your_storage_account>,請使用儲存體帳戶的名稱。Use the name of your Storage account for <your_storage_account>. 對於 <your_storage_account_key>,請使用 Azure 入口網站中列出的儲存體帳戶存取金鑰。For <your_storage_account_key>, use the access key for the Storage account listed in the Azure portal. 如需有關儲存體帳戶和存取金鑰的資訊,請參閱建立儲存體帳戶For information on Storage accounts and access keys, see Create a storage account.

設定 Azure Cosmos DB 連接字串Set up an Azure Cosmos DB connection string

本範例會示範如何宣告靜態欄位來存放 Azure Cosmos DB 連接字串:This example shows how to declare a static field to hold the Azure Cosmos DB connection string:

// Define the Azure Cosmos DB connection string with your values.
const utility::string_t storage_connection_string(U("DefaultEndpointsProtocol=https;AccountName=<your_cosmos_db_account>;AccountKey=<your_cosmos_db_account_key>;TableEndpoint=<your_cosmos_db_endpoint>"));

對於 <your_cosmos_db_account>,請使用 Azure Cosmos DB 帳戶的名稱。Use the name of your Azure Cosmos DB account for <your_cosmos_db_account>. 對於 <your_cosmos_db_account_key>,請輸入您的主索引鍵。Enter your primary key for <your_cosmos_db_account_key>. 對於 <your_cosmos_db_endpoint>,請輸入 Azure 入口網站中列出的端點。Enter the endpoint listed in the Azure portal for <your_cosmos_db_endpoint>.

若要在本機 Windows 電腦中測試您的應用程式,可以使用隨 Azure SDK 一起安裝的 Azure 儲存體模擬器。To test your application in your local Windows-based computer, you can use the Azure Storage Emulator that is installed with the Azure SDK. 儲存體模擬器是一個公用程式,可模擬本機開發電腦上的 Azure Blob、佇列和表格服務。The Storage Emulator is a utility that simulates the Azure Blob, Queue, and Table services available on your local development machine. 下列範例會示範如何宣告靜態欄位,以便將連接字串存放到本機儲存體模擬器中:The following example shows how to declare a static field to hold the connection string to your local storage emulator:

// Define the connection string with Azure Storage Emulator.
const utility::string_t storage_connection_string(U("UseDevelopmentStorage=true;"));  

若要啟動 Azure 儲存體模擬器,請從 Windows 桌面選取 [開始] 按鈕或 Windows 鍵。To start the Azure Storage Emulator, from your Windows desktop, select the Start button or the Windows key. 輸入並執行 Microsoft Azure 儲存體模擬器Enter and run Microsoft Azure Storage Emulator. 如需詳細資訊,請參閱使用 Azure 儲存體模擬器進行開發和測試For more information, see Use the Azure Storage Emulator for development and testing.

擷取連接字串Retrieve your connection string

您可以使用 cloud_storage_account 類別來代表儲存體帳戶資訊。You can use the cloud_storage_account class to represent your storage account information. 若要從儲存體連接字串擷取儲存體帳戶資訊,請使用 parse 方法。To retrieve your storage account information from the storage connection string, use the parse method.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

接著,取得 cloud_table_client 類別的參考。Next, get a reference to a cloud_table_client class. 此類別可讓您取得資料表儲存體服務內儲存的資料表和實體的參考物件。This class lets you get reference objects for tables and entities stored within the Table storage service. 下列程式碼會使用先前擷取的儲存體帳戶物件建立 cloud_table_client 物件:The following code creates a cloud_table_client object by using the storage account object you retrieved previously:

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

建立實體並新增至資料表Create and add entities to a table

建立資料表Create a table

cloud_table_client 物件可讓您取得資料表和實體的參照物件。A cloud_table_client object lets you get reference objects for tables and entities. 下列程式碼會建立 cloud_table_client 物件,並使用該物件建立新資料表。The following code creates a cloud_table_client object and uses it to create a new table.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);  

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Retrieve a reference to a table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Create the table if it doesn't exist.
table.create_if_not_exists();  

將實體新增至資料表Add an entity to a table

若要將實體新增至資料表,請建立新的 table_entity 物件,並將它傳遞給 table_operation::insert_entityTo add an entity to a table, create a new table_entity object and pass it to table_operation::insert_entity. 下列程式碼會使用客戶名字做為資料列索引鍵,並使用姓氏做為資料分割索引鍵。The following code uses the customer's first name as the row key and last name as the partition key. 實體的資料分割索引鍵和資料列索引鍵共同唯一識別資料表中的實體。Together, an entity's partition and row key uniquely identify the entity in the table. 相較於查詢具有不同資料分割索引鍵的實體,查詢具有相同資料分割索引鍵的實體速度會較快。Entities with the same partition key can be queried faster than entities with different partition keys. 使用不同的分割索引鍵,可提供更大的平行作業延展性。Using diverse partition keys allows for greater parallel operation scalability. 如需詳細資訊,請參閱 Microsoft Azure 儲存體效能與延展性檢查清單For more information, see Microsoft Azure storage performance and scalability checklist.

下列程式碼會建立 table_entity 的新執行個體,其中含有一些要儲存的客戶資料。The following code creates a new instance of table_entity with some customer data to store. 程式碼接著會呼叫 table_operation::insert_entity 來建立 table_operation 物件,以便將實體插入資料表中,並將新的資料表與該物件建立關聯。The code next calls table_operation::insert_entity to create a table_operation object to insert an entity into a table, and associates the new table entity with it. 最後,程式碼會針對 cloud_table 物件呼叫 execute 方法。Finally, the code calls the execute method on the cloud_table object. 新的 table_operation 會傳送一個要求到表格服務,以便將新的客戶實體插入到 people 資料表。The new table_operation sends a request to the Table service to insert the new customer entity into the people table.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Retrieve a reference to a table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Create the table if it doesn't exist.
table.create_if_not_exists();

// Create a new customer entity.
azure::storage::table_entity customer1(U("Harp"), U("Walter"));

azure::storage::table_entity::properties_type& properties = customer1.properties();
properties.reserve(2);
properties[U("Email")] = azure::storage::entity_property(U("Walter@contoso.com"));

properties[U("Phone")] = azure::storage::entity_property(U("425-555-0101"));

// Create the table operation that inserts the customer entity.
azure::storage::table_operation insert_operation = azure::storage::table_operation::insert_entity(customer1);

// Execute the insert operation.
azure::storage::table_result insert_result = table.execute(insert_operation);

插入一批實體Insert a batch of entities

您可以在單一寫入操作中,插入實體批次至資料表服務。You can insert a batch of entities to the Table service in one write operation. 下列程式碼會建立一個 table_batch_operation 物件,然後在其中新增三個插入操作。The following code creates a table_batch_operation object, and then adds three insert operations to it. 新增插入作業的方式都是建立新的實體物件、設定其值,然後呼叫 table_batch_operation 物件上的 insert 方法以將實體與新的插入操作建立關聯。Each insert operation is added by creating a new entity object, setting its values, and then calling the insert method on the table_batch_operation object to associate the entity with a new insert operation. 然後,程式碼會呼叫 cloud_table.execute 執行作業。Then, the code calls cloud_table.execute to run the operation.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Define a batch operation.
azure::storage::table_batch_operation batch_operation;

// Create a customer entity and add it to the table.
azure::storage::table_entity customer1(U("Smith"), U("Jeff"));

azure::storage::table_entity::properties_type& properties1 = customer1.properties();
properties1.reserve(2);
properties1[U("Email")] = azure::storage::entity_property(U("Jeff@contoso.com"));
properties1[U("Phone")] = azure::storage::entity_property(U("425-555-0104"));

// Create another customer entity and add it to the table.
azure::storage::table_entity customer2(U("Smith"), U("Ben"));

azure::storage::table_entity::properties_type& properties2 = customer2.properties();
properties2.reserve(2);
properties2[U("Email")] = azure::storage::entity_property(U("Ben@contoso.com"));
properties2[U("Phone")] = azure::storage::entity_property(U("425-555-0102"));

// Create a third customer entity to add to the table.
azure::storage::table_entity customer3(U("Smith"), U("Denise"));

azure::storage::table_entity::properties_type& properties3 = customer3.properties();
properties3.reserve(2);
properties3[U("Email")] = azure::storage::entity_property(U("Denise@contoso.com"));
properties3[U("Phone")] = azure::storage::entity_property(U("425-555-0103"));

// Add customer entities to the batch insert operation.
batch_operation.insert_or_replace_entity(customer1);
batch_operation.insert_or_replace_entity(customer2);
batch_operation.insert_or_replace_entity(customer3);

// Execute the batch operation.
std::vector<azure::storage::table_result> results = table.execute_batch(batch_operation);

以下是批次操作的一些注意事項:Some things to note on batch operations:

  • 在單一批次中,最多可以執行 100 個 insertdeletemergereplaceinsert-or-mergeinsert-or-replace 作業的任何組合。You can do up to 100 insert, delete, merge, replace, insert-or-merge, and insert-or-replace operations in any combination in a single batch.
  • 當擷取操作是批次中的唯一操作時,批次操作可以包含擷取操作。A batch operation can have a retrieve operation, if it's the only operation in the batch.
  • 單一批次操作中的所有實體必須具有相同的資料分割索引鍵。All entities in a single batch operation must have the same partition key.
  • 一個批次操作的資料裝載限制為 4MB。A batch operation is limited to a 4-MB data payload.

查詢和修改實體Query and modify entities

擷取資料分割中的所有實體Retrieve all entities in a partition

若要向資料表查詢資料分割中的所有實體,請使用 table_query 物件。To query a table for all entities in a partition, use a table_query object. 下列程式碼範例會指定篩選器來篩選出資料分割索引鍵為 Smith 的實體。The following code example specifies a filter for entities where Smith is the partition key. 此範例會將查詢結果中每個實體的欄位列印至主控台。This example prints the fields of each entity in the query results to the console.

注意

在 Azure Cosmos DB 中,C++ 目前不支援這些方法。These methods are not currently supported for C++ in Azure Cosmos DB.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Construct the query operation for all customer entities where PartitionKey="Smith".
azure::storage::table_query query;

query.set_filter_string(azure::storage::table_query::generate_filter_condition(U("PartitionKey"), azure::storage::query_comparison_operator::equal, U("Smith")));

// Execute the query.
azure::storage::table_query_iterator it = table.execute_query(query);

// Print the fields for each customer.
azure::storage::table_query_iterator end_of_results;
for (; it != end_of_results; ++it)
{
    const azure::storage::table_entity::properties_type& properties = it->properties();

    std::wcout << U("PartitionKey: ") << it->partition_key() << U(", RowKey: ") << it->row_key()
        << U(", Property1: ") << properties.at(U("Email")).string_value()
        << U(", Property2: ") << properties.at(U("Phone")).string_value() << std::endl;
}  

此範例中的查詢會傳回符合篩選準則的所有實體。The query in this example returns all the entities that match the filter criteria. 如果您有大型資料表,而必需要經常下載資料表實體,建議您將資料改為儲存在 Azure 儲存體 Blob 中。If you have large tables and need to download the table entities often, we recommend that you store your data in Azure storage blobs instead.

擷取資料分割中某個範圍的實體Retrieve a range of entities in a partition

如果您不想要查詢資料分割中的所有實體,可以指定範圍。If you don't want to query all the entities in a partition, you can specify a range. 結合資料分割索引鍵篩選條件與資料列索引鍵篩選條件。Combine the partition key filter with a row key filter. 下列程式碼範例會使用兩個篩選器來取得資料分割 Smith 中,資料列索引鍵 (名字) 是以字母 E 前之字母為開頭的所有實體,然後會列印查詢結果。The following code example uses two filters to get all entities in partition Smith where the row key (first name) starts with a letter earlier than E in the alphabet, and then prints the query results.

注意

在 Azure Cosmos DB 中,C++ 目前不支援這些方法。These methods are not currently supported for C++ in Azure Cosmos DB.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Create the table query.
azure::storage::table_query query;

query.set_filter_string(azure::storage::table_query::combine_filter_conditions(
    azure::storage::table_query::generate_filter_condition(U("PartitionKey"),
    azure::storage::query_comparison_operator::equal, U("Smith")),
    azure::storage::query_logical_operator::op_and,
    azure::storage::table_query::generate_filter_condition(U("RowKey"), azure::storage::query_comparison_operator::less_than, U("E"))));

// Execute the query.
azure::storage::table_query_iterator it = table.execute_query(query);

// Loop through the results, displaying information about the entity.
azure::storage::table_query_iterator end_of_results;
for (; it != end_of_results; ++it)
{
    const azure::storage::table_entity::properties_type& properties = it->properties();

    std::wcout << U("PartitionKey: ") << it->partition_key() << U(", RowKey: ") << it->row_key()
        << U(", Property1: ") << properties.at(U("Email")).string_value()
        << U(", Property2: ") << properties.at(U("Phone")).string_value() << std::endl;
}  

擷取單一實體Retrieve a single entity

您可以撰寫查詢來擷取單一特定實體。You can write a query to retrieve a single, specific entity. 下列程式碼會使用 table_operation::retrieve_entity 來指定客戶 Jeff SmithThe following code uses table_operation::retrieve_entity to specify the customer Jeff Smith. 此方法只會傳回一個實體而非一個集合,且傳回的值位於 table_result 中。This method returns just one entity, rather than a collection, and the returned value is in table_result. 若要從資料表服務中擷取單一實體,最快的方法是在查詢中同時指定資料分割索引鍵和資料列索引鍵。Specifying both partition and row keys in a query is the fastest way to retrieve a single entity from the Table service.

azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Retrieve the entity with partition key of "Smith" and row key of "Jeff".
azure::storage::table_operation retrieve_operation = azure::storage::table_operation::retrieve_entity(U("Smith"), U("Jeff"));
azure::storage::table_result retrieve_result = table.execute(retrieve_operation);

// Output the entity.
azure::storage::table_entity entity = retrieve_result.entity();
const azure::storage::table_entity::properties_type& properties = entity.properties();

std::wcout << U("PartitionKey: ") << entity.partition_key() << U(", RowKey: ") << entity.row_key()
    << U(", Property1: ") << properties.at(U("Email")).string_value()
    << U(", Property2: ") << properties.at(U("Phone")).string_value() << std::endl;

取代實體Replace an entity

若要更新實體,請從資料表服務擷取該實體、修改實體物件,然後將變更儲存回資料表服務。To replace an entity, retrieve it from the Table service, modify the entity object, and then save the changes back to the Table service. 下列程式碼會變更現有客戶的電話號碼和電子郵件地址。The following code changes an existing customer's phone number and email address. 此程式碼不會呼叫 table_operation::insert_entity,而會使用 table_operation::replace_entityInstead of calling table_operation::insert_entity, this code uses table_operation::replace_entity. 這種方法會完全取代伺服器上的實體,除非伺服器上的實體自擷取後產生變化。This approach causes the entity to be fully replaced on the server, unless the entity on the server has changed since it was retrieved. 如果有所變更,該操作就會失敗。If it has been changed, the operation fails. 這項失敗會防止應用程式覆寫其他元件在擷取後到更新前的這段期間所做的變更。This failure prevents your application from overwriting a change made between the retrieval and update by another component. 正確處理此失敗的方式為重新擷取實體、進行變更 (如果仍然有效),然後再執行一次 table_operation::replace_entity 作業。The proper handling of this failure is to retrieve the entity again, make your changes, if still valid, and then do another table_operation::replace_entity operation.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Replace an entity.
azure::storage::table_entity entity_to_replace(U("Smith"), U("Jeff"));
azure::storage::table_entity::properties_type& properties_to_replace = entity_to_replace.properties();
properties_to_replace.reserve(2);

// Specify a new phone number.
properties_to_replace[U("Phone")] = azure::storage::entity_property(U("425-555-0106"));

// Specify a new email address.
properties_to_replace[U("Email")] = azure::storage::entity_property(U("JeffS@contoso.com"));

// Create an operation to replace the entity.
azure::storage::table_operation replace_operation = azure::storage::table_operation::replace_entity(entity_to_replace);

// Submit the operation to the Table service.
azure::storage::table_result replace_result = table.execute(replace_operation);

插入或取代實體Insert or replace an entity

如果從伺服器擷取的實體自擷取後發生變化,table_operation::replace_entity 作業將失敗。table_operation::replace_entity operations fail if the entity has been changed since it was retrieved from the server. 此外,您必須先從伺服器擷取實體,table_operation::replace_entity 作業才會成功。Furthermore, you must retrieve the entity from the server first in order for table_operation::replace_entity to be successful. 有時候,您不知道該實體是否存在於伺服器上。Sometimes, you don't know if the entity exists on the server. 目前儲存其中的值並不重要,因為您的更新應當會將值全數覆寫。The current values stored in it are irrelevant, because your update should overwrite them all. 若要達成此結果,請使用 table_operation::insert_or_replace_entity 作業。To accomplish this result, use a table_operation::insert_or_replace_entity operation. 如果實體不存在,這項作業會插入實體。This operation inserts the entity if it doesn't exist. 如果實體存在,這項作業就會取代該實體。The operation replaces the entity if it exists. 在下列程式碼範例中,仍會擷取 Jeff Smith 的客戶實體,但接著會使用 table_operation::insert_or_replace_entity 儲存回伺服器。In the following code example, the customer entity for Jeff Smith is still retrieved, but it's then saved back to the server by using table_operation::insert_or_replace_entity. 在擷取後到更新前的這段期間對實體所做的任何更新,都會遭到覆寫。Any updates made to the entity between the retrieval and update operation will be overwritten.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Insert or replace an entity.
azure::storage::table_entity entity_to_insert_or_replace(U("Smith"), U("Jeff"));
azure::storage::table_entity::properties_type& properties_to_insert_or_replace = entity_to_insert_or_replace.properties();

properties_to_insert_or_replace.reserve(2);

// Specify a phone number.
properties_to_insert_or_replace[U("Phone")] = azure::storage::entity_property(U("425-555-0107"));

// Specify an email address.
properties_to_insert_or_replace[U("Email")] = azure::storage::entity_property(U("Jeffsm@contoso.com"));

// Create an operation to insert or replace the entity.
azure::storage::table_operation insert_or_replace_operation = azure::storage::table_operation::insert_or_replace_entity(entity_to_insert_or_replace);

// Submit the operation to the Table service.
azure::storage::table_result insert_or_replace_result = table.execute(insert_or_replace_operation);

查詢實體屬性的子集Query a subset of entity properties

一項資料表查詢可以只擷取實體的少數屬性。A query to a table can retrieve just a few properties from an entity. 下列程式碼中的查詢會使用 table_query::set_select_columns 方法,只傳回資料表中實體的電子郵件地址。The query in the following code uses the table_query::set_select_columns method to return only the email addresses of entities in the table.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Define the query, and select only the Email property.
azure::storage::table_query query;
std::vector<utility::string_t> columns;

columns.push_back(U("Email"));
query.set_select_columns(columns);

// Execute the query.
azure::storage::table_query_iterator it = table.execute_query(query);

// Display the results.
azure::storage::table_query_iterator end_of_results;
for (; it != end_of_results; ++it)
{
    std::wcout << U("PartitionKey: ") << it->partition_key() << U(", RowKey: ") << it->row_key();

    const azure::storage::table_entity::properties_type& properties = it->properties();
    for (auto prop_it = properties.begin(); prop_it != properties.end(); ++prop_it)
    {
        std::wcout << ", " << prop_it->first << ": " << prop_it->second.str();
    }

    std::wcout << std::endl;
}

注意

從實體查詢一些屬性比擷取所有屬性更有效率。Querying a few properties from an entity is a more efficient operation than retrieving all properties.

刪除內容Delete content

刪除實體Delete an entity

擷取實體之後,即可刪除。You can delete an entity after you retrieve it. 在您擷取實體之後,請以要刪除的實體呼叫 table_operation::delete_entityAfter you retrieve an entity, call table_operation::delete_entity with the entity to delete. 接著呼叫 cloud_table.execute 方法。Then call the cloud_table.execute method. 下列程式碼會擷取並刪除資料分割索引鍵為 Smith 且資料列索引鍵為 Jeff 的實體。The following code retrieves and deletes an entity with a partition key of Smith and a row key of Jeff.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Create an operation to retrieve the entity with partition key of "Smith" and row key of "Jeff".
azure::storage::table_operation retrieve_operation = azure::storage::table_operation::retrieve_entity(U("Smith"), U("Jeff"));
azure::storage::table_result retrieve_result = table.execute(retrieve_operation);

// Create an operation to delete the entity.
azure::storage::table_operation delete_operation = azure::storage::table_operation::delete_entity(retrieve_result.entity());

// Submit the delete operation to the Table service.
azure::storage::table_result delete_result = table.execute(delete_operation);  

刪除資料表Delete a table

最後,下列程式碼範例會從儲存體帳戶刪除資料表。Finally, the following code example deletes a table from a storage account. 資料表在刪除後的一段時間內,會無法重新建立。A table that has been deleted is unavailable to be re-created for some time following the deletion.

// Retrieve the storage account from the connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the table client.
azure::storage::cloud_table_client table_client = storage_account.create_cloud_table_client();

// Create a cloud table object for the table.
azure::storage::cloud_table table = table_client.get_table_reference(U("people"));

// Delete the table if it exists
if (table.delete_table_if_exists())
{
    std::cout << "Table deleted!";
}
else
{
    std::cout << "Table didn't exist";
}

疑難排解Troubleshooting

對於 Visual Studio Community Edition,如果您的專案因為包含 storage_account.htable.h 檔案而發生建置錯誤,請移除 /permissive- 編譯器參數:For Visual Studio Community Edition, if your project gets build errors because of the include files storage_account.h and table.h, remove the /permissive- compiler switch:

  1. 方案總管 中,於您的專案上按一下滑鼠右鍵,然後選取 [屬性] 。In Solution Explorer, right-click your project and select Properties.
  2. 在 [屬性頁] 對話方塊方塊中,依序展開 [組態屬性] 和 [C/C++] ,然後選取 [語言] 。In the Property Pages dialog box, expand Configuration Properties, expand C/C++, and select Language.
  3. 將 [一致性模式] 設定為 [否] 。Set Conformance mode to No.

後續步驟Next steps

Microsoft Azure 儲存體總管 是一個免費的獨立應用程式,可讓您在 Windows、MacOS 和 Linux 上以視覺化方式處理 Azure 儲存體資料。Microsoft Azure Storage Explorer is a free, standalone app from Microsoft that enables you to work visually with Azure Storage data on Windows, macOS, and Linux.

請遵循下列連結,以深入了解 Azure Cosmos DB 中的 Azure 儲存體和資料表 API:Follow these links to learn more about Azure Storage and the Table API in Azure Cosmos DB: