如何使用 PHP 的 Azure 儲存體表格服務或 Azure Cosmos DB 資料表 APIHow to use Azure Storage Table service or the Azure Cosmos DB Table API from PHP

適用於: 資料表 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.

本文說明如何建立資料表、儲存您的資料,以及對資料執行 CRUD 作業。This article shows you how to create tables, store your data, and perform CRUD operations on the data. 選擇 Azure 資料表服務或 Azure Cosmos DB 資料表 API。Choose either the Azure Table service or the Azure Cosmos DB Table API. 這些範例是以 PHP 撰寫,並且使用 Azure 儲存體資料表 PHP 用戶端程式庫The samples are written in PHP and use the Azure Storage Table PHP Client Library. 所涵蓋的案例包括 建立和刪除資料表 以及 在資料表中插入、刪除及查詢實體The scenarios covered include creating and deleting a table , and inserting, deleting, and querying entities in a table. 如需有關 Azure 資料表服務的詳細資訊,請參閱 後續步驟 一節。For more information on the Azure Table service, see the Next steps section.

建立 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.

建立 PHP 應用程式Create a PHP application

建立 PHP 應用程式以存取儲存體表格服務或 Azure Cosmos DB 資料表 API 的唯一需求,就是從您的程式碼中參考適用於 PHP 之 azure-storage-table SDK 的類別。The only requirement to create a PHP application to access the Storage Table service or Azure Cosmos DB Table API is to reference classes in the azure-storage-table SDK for PHP from within your code. 您可以使用任何開發工具來建立應用程式 (包括 [記事本])。You can use any development tools to create your application, including Notepad.

在本指南中,您使用可從 PHP 應用程式內本機呼叫的儲存體表格服務或 Azure Cosmos DB 功能,或可從 Azure Web 角色、背景工作角色或網站內執行的程式碼中呼叫的表格服務功能。In this guide, you use Storage Table service or Azure Cosmos DB features that can be called from within a PHP application locally, or in code running within an Azure web role, worker role, or website.

取得用戶端程式庫Get the client library

  1. 在專案的根目錄中建立名為 composer.json 的檔案,並新增下列程式碼:Create a file named composer.json in the root of your project and add the following code to it:
    {
    "require": {
     "microsoft/azure-storage-table": "*"
    }
    }
    
  2. composer.phar 下載到根目錄中。Download composer.phar in your root.
  3. 開啟命令提示字元,在專案根目錄中執行下列命令:Open a command prompt and execute the following command in your project root:
    php composer.phar install
    
    或者,移至 GitHub 上的 Azure 儲存體資料表 PHP 用戶端程式庫來複製原始程式碼。Alternatively, go to the Azure Storage Table PHP Client Library on GitHub to clone the source code.

新增必要的參考Add required references

若要使用儲存體表格服務或 Azure Cosmos DB API,您必須:To use the Storage Table service or Azure Cosmos DB APIs, you must:

  • 參考使用 require_once 陳述式的自動載入器檔案,以及Reference the autoloader file using the require_once statement, and
  • 參考您使用的任何類別。Reference any classes you use.

下列範例會示範如何納入自動換片器檔案及參考 TableRestProxy 類別。The following example shows how to include the autoloader file and reference the TableRestProxy class.

require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Table\TableRestProxy;

在下列各範例中,一律會顯示 require_once 陳述式,但只會參考要執行之範例所需的類別。In the examples below, the require_once statement is always shown, but only the classes necessary for the example to execute are referenced.

新增連接字串Add your connection string

您可以連線到 Azure 儲存體帳戶或 Azure Cosmos DB 資料表 API 帳戶。You can either connect to the Azure storage account or the Azure Cosmos DB Table API account. 根據您使用的帳戶類型,取得連接字串。Get the connection string based on the type of account you are using.

新增儲存體表格服務連線Add a Storage Table service connection

若要具現化儲存體表格服務用戶端,您必須先具備一個有效的連接字串。To instantiate a Storage Table service client, you must first have a valid connection string. 儲存體表格服務的連接字串格式為:The format for the Storage Table service connection string is:

$connectionString = "DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]"

新增儲存體模擬器連線Add a Storage Emulator connection

若要存取模擬器儲存體:To access the emulator storage:

UseDevelopmentStorage = true

新增 Azure Cosmos DB 連線Add an Azure Cosmos DB connection

若要具現化 Azure Cosmos DB 資料表用戶端,您必須先具備一個有效的連接字串。To instantiate an Azure Cosmos DB Table client, you must first have a valid connection string. Azure Cosmos DB 連接字串的格式如下:The format for the Azure Cosmos DB connection string is:

$connectionString = "DefaultEndpointsProtocol=[https];AccountName=[myaccount];AccountKey=[myaccountkey];TableEndpoint=[https://myendpoint/]";

若要建立 Azure 表格服務用戶端或 Azure Cosmos DB 用戶端,您必須使用 TableRestProxy 類別。To create an Azure Table service client or Azure Cosmos DB client, you need to use the TableRestProxy class. 您可以:You can:

  • 直接將連接字串傳遞給它,或Pass the connection string directly to it or
  • 使用 CloudConfigurationManager (CCM) 到多種外部來源檢查連接字串:Use the CloudConfigurationManager (CCM) to check multiple external sources for the connection string:
    • 預設已支援一種外部來源,即環境變數By default, it comes with support for one external source - environmental variables.
    • 您可以擴充 ConnectionStringSource 類別以加入新來源。You can add new sources by extending the ConnectionStringSource class.

在本文的各範例中,將會直接傳遞連接字串。For the examples outlined here, the connection string is passed directly.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;

$tableClient = TableRestProxy::createTableService($connectionString);

建立資料表Create a table

TableRestProxy 物件可讓您以 createTable 方法建立資料表。A TableRestProxy object lets you create a table with the createTable method. 建立資料表時,您可以設定資料表服務逾時值。When creating a table, you can set the Table service timeout. (如需有關表格服務逾時值的詳細資訊,請參閱設定表格服務作業的逾時值。)(For more information about the Table service timeout, see Setting Timeouts for Table Service Operations.)

require_once 'vendor\autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create Table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    // Create table.
    $tableClient->createTable("mytable");
}
catch(ServiceException $e){
    $code = $e->getCode();
    $error_message = $e->getMessage();
    // Handle exception based on error codes and messages.
    // Error codes and messages can be found here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
}

如需有關資料表名稱限制的資訊,請參閱了解表格服務資料模型For information about restrictions on table names, see Understanding the Table Service Data Model.

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

若要將實體新增至資料表,請建立一個新的 Entity 物件,然後將它傳遞給 TableRestProxy->insertEntityTo add an entity to a table, create a new Entity object and pass it to TableRestProxy->insertEntity. 請注意,建立實體時,您必須指定 PartitionKeyRowKeyNote that when you create an entity, you must specify a PartitionKey and RowKey. 這些是實體的唯一識別碼,且其值的查詢速度比其他屬性快上許多。These are the unique identifiers for an entity and are values that can be queried much faster than other entity properties. 系統使用 PartitionKey 自動將資料表的實體散發在許多儲存體節點上。The system uses PartitionKey to automatically distribute the table's entities over many Storage nodes. 具有相同 PartitionKey 的實體會儲存在相同節點上。Entities with the same PartitionKey are stored on the same node. (對儲存在同一節點上的多個實體執行作業,會比對儲存在不同節點上的實體執行作業有更佳的執行效果。)RowKey 是實體在分割內的唯一識別碼。(Operations on multiple entities stored on the same node perform better than on entities stored across different nodes.) The RowKey is the unique ID of an entity within a partition.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$entity = new Entity();
$entity->setPartitionKey("tasksSeattle");
$entity->setRowKey("1");
$entity->addProperty("Description", null, "Take out the trash.");
$entity->addProperty("DueDate",
                        EdmType::DATETIME,
                        new DateTime("2012-11-05T08:15:00-08:00"));
$entity->addProperty("Location", EdmType::STRING, "Home");

try{
    $tableClient->insertEntity("mytable", $entity);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
}

如需有關資料表屬性和類型的資訊,請參閱了解表格服務資料模型For information about Table properties and types, see Understanding the Table Service Data Model.

TableRestProxy 類別提供兩種插入實體的替代方法: insertOrMergeEntityinsertOrReplaceEntityThe TableRestProxy class offers two alternative methods for inserting entities: insertOrMergeEntity and insertOrReplaceEntity. 若要使用這些方法,請建立一個新的 Entity ,然後將它當做參數傳遞給其中一個方法。To use these methods, create a new Entity and pass it as a parameter to either method. 只要實體不存在,每個方法都會插入實體。Each method will insert the entity if it does not exist. 如果實體已經存在, insertOrMergeEntity 會在屬性已經存在時更新屬性值,並在屬性不存在時新增屬性,而 insertOrReplaceEntity 則是會完全取代現有的實體。If the entity already exists, insertOrMergeEntity updates property values if the properties already exist and adds new properties if they do not exist, while insertOrReplaceEntity completely replaces an existing entity. 下列範例示範如何使用 insertOrMergeEntityThe following example shows how to use insertOrMergeEntity. 如果 PartitionKey 為「tasksSeattle」且 RowKey 為「1」的實體尚未存在,便會將之插入。If the entity with PartitionKey "tasksSeattle" and RowKey "1" does not already exist, it will be inserted. 不過,如果先前已經插入 insertOrMergeEntity (如上述範例所示),方法便會更新 DueDate 屬性並新增 Status 屬性。However, if it has previously been inserted (as shown in the example above), the DueDate property is updated, and the Status property is added. DescriptionLocation 屬性也會更新,但是所使用的值實際上會讓它們保持不變。The Description and Location properties are also updated, but with values that effectively leave them unchanged. 如果如範例中所示並未新增後面兩個屬性,但這兩個屬性存在於目標實體上,它們現有的值就會保持不變。If these latter two properties were not added as shown in the example, but existed on the target entity, their existing values would remain unchanged.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

//Create new entity.
$entity = new Entity();

// PartitionKey and RowKey are required.
$entity->setPartitionKey("tasksSeattle");
$entity->setRowKey("1");

// If entity exists, existing properties are updated with new values and
// new properties are added. Missing properties are unchanged.
$entity->addProperty("Description", null, "Take out the trash.");
$entity->addProperty("DueDate", EdmType::DATETIME, new DateTime()); // Modified the DueDate field.
$entity->addProperty("Location", EdmType::STRING, "Home");
$entity->addProperty("Status", EdmType::STRING, "Complete"); // Added Status field.

try    {
    // Calling insertOrReplaceEntity, instead of insertOrMergeEntity as shown,
    // would simply replace the entity with PartitionKey "tasksSeattle" and RowKey "1".
    $tableClient->insertOrMergeEntity("mytable", $entity);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

擷取單一實體Retrieve a single entity

TableRestProxy->getEntityRowKey 方法可讓您透過查詢其PartitionKey 來擷取單一實體。The TableRestProxy->getEntity method allows you to retrieve a single entity by querying for its PartitionKey and RowKey. 在以下範例中,會將分割區索引鍵 tasksSeattle 和資料列索引鍵 1 傳遞給 getEntity 方法。In the example below, the partition key tasksSeattle and row key 1 are passed to the getEntity method.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    $result = $tableClient->getEntity("mytable", "tasksSeattle", 1);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

$entity = $result->getEntity();

echo $entity->getPartitionKey().":".$entity->getRowKey();

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

實體查詢使用篩選條件建構而成 (如需詳細資訊,請參閱查詢資料表和實體)。Entity queries are constructed using filters (for more information, see Querying Tables and Entities). 若要擷取資料分割中的所有實體,請使用 "PartitionKey eq partition_name " 篩選條件。To retrieve all entities in partition, use the filter "PartitionKey eq partition_name ". 下列範例示範如何透過將篩選條件傳遞給 queryEntities 方法來擷取 tasksSeattle 分割中的所有實體。The following example shows how to retrieve all entities in the tasksSeattle partition by passing a filter to the queryEntities method.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$filter = "PartitionKey eq 'tasksSeattle'";

try    {
    $result = $tableClient->queryEntities("mytable", $filter);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

$entities = $result->getEntities();

foreach($entities as $entity){
    echo $entity->getPartitionKey().":".$entity->getRowKey()."<br />";
}

擷取資料分割中實體的子集Retrieve a subset of entities in a partition

前面範例中所使用的相同模式可用來擷取資料分割中的任何實體子集。The same pattern used in the previous example can be used to retrieve any subset of entities in a partition. 您所擷取的實體子集將取決於您使用的篩選條件 (如需詳細資訊,請參閱查詢資料表和實體)。下列範例示範如何使用篩選條件擷取位於特定 LocationDueDate 在指定日期之前的所有實體。The subset of entities you retrieve are determined by the filter you use (for more information, see Querying Tables and Entities).The following example shows how to use a filter to retrieve all entities with a specific Location and a DueDate less than a specified date.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$filter = "Location eq 'Office' and DueDate lt '2012-11-5'";

try    {
    $result = $tableClient->queryEntities("mytable", $filter);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

$entities = $result->getEntities();

foreach($entities as $entity){
    echo $entity->getPartitionKey().":".$entity->getRowKey()."<br />";
}

擷取實體屬性的子集Retrieve a subset of entity properties

查詢可以擷取實體屬性的子集。A query can retrieve a subset of entity properties. 這項稱為「投射」 的技術可減少頻寬並提高查詢效能 (尤其是對大型實體而言)。This technique, called projection , reduces bandwidth and can improve query performance, especially for large entities. 若要指定要擷取的屬性,請將屬性的名稱傳遞給 Query->addSelectField 方法。To specify a property to retrieve, pass the name of the property to the Query->addSelectField method. 您可以呼叫此方法許多次以新增其他屬性。You can call this method multiple times to add more properties. 執行 TableRestProxy->queryEntities 之後,傳回的實體將只具有選取的屬性。After executing TableRestProxy->queryEntities , the returned entities will only have the selected properties. (如果您想要傳回資料表實體的子集,請使用篩選條件,如上面的查詢所示。)(If you want to return a subset of Table entities, use a filter as shown in the queries above.)

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\QueryEntitiesOptions;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$options = new QueryEntitiesOptions();
$options->addSelectField("Description");

try    {
    $result = $tableClient->queryEntities("mytable", $options);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

// All entities in the table are returned, regardless of whether
// they have the Description field.
// To limit the results returned, use a filter.
$entities = $result->getEntities();

foreach($entities as $entity){
    $description = $entity->getProperty("Description")->getValue();
    echo $description."<br />";
}

更新實體Update an entity

您可以藉由對實體使用 Entity->setPropertyEntity->addProperty 方法,然後呼叫 TableRestProxy->updateEntity ,來更新現有實體。You can update an existing entity by using the Entity->setProperty and Entity->addProperty methods on the entity, and then calling TableRestProxy->updateEntity. 下列範例會擷取一個實體、修改一個屬性、移除另一個屬性,以及新增一個屬性。The following example retrieves an entity, modifies one property, removes another property, and adds a new property. 請注意,移除屬性的方式是將它的值設定成 nullNote that you can remove a property by setting its value to null.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

$result = $tableClient->getEntity("mytable", "tasksSeattle", 1);

$entity = $result->getEntity();
$entity->setPropertyValue("DueDate", new DateTime()); //Modified DueDate.
$entity->setPropertyValue("Location", null); //Removed Location.
$entity->addProperty("Status", EdmType::STRING, "In progress"); //Added Status.

try    {
    $tableClient->updateEntity("mytable", $entity);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

刪除實體Delete an entity

若要刪除實體,請將資料表名稱以及實體的 PartitionKeyRowKey 傳遞給 TableRestProxy->deleteEntity 方法。To delete an entity, pass the table name, and the entity's PartitionKey and RowKey to the TableRestProxy->deleteEntity method.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    // Delete entity.
    $tableClient->deleteEntity("mytable", "tasksSeattle", "2");
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

針對並行檢查,您可以使用 DeleteEntityOptions->setEtag 方法為要刪除的實體設定 Etag,並將 DeleteEntityOptions 物件傳遞給 deleteEntity 作為第四個參數。For concurrency checks, you can set the Etag for an entity to be deleted by using the DeleteEntityOptions->setEtag method and passing the DeleteEntityOptions object to deleteEntity as a fourth parameter.

批次資料表作業Batch table operations

TableRestProxy->batch 方法可讓您以單一要求執行多項作業。The TableRestProxy->batch method allows you to execute multiple operations in a single request. 這裡的模式涉及將作業新增至 BatchRequest 物件,然後將 BatchRequest 物件傳遞給 TableRestProxy->batch 方法。The pattern here involves adding operations to BatchRequest object and then passing the BatchRequest object to the TableRestProxy->batch method. 若要將作業新增至 BatchRequest 物件,您可以呼叫下列任一方法許多次:To add an operation to a BatchRequest object, you can call any of the following methods multiple times:

  • addInsertEntity (新增 insertEntity 作業)addInsertEntity (adds an insertEntity operation)
  • addUpdateEntity (新增 updateEntity 作業)addUpdateEntity (adds an updateEntity operation)
  • addMergeEntity (新增 mergeEntity 作業)addMergeEntity (adds a mergeEntity operation)
  • addInsertOrReplaceEntity (新增 insertOrReplaceEntity 作業)addInsertOrReplaceEntity (adds an insertOrReplaceEntity operation)
  • addInsertOrMergeEntity (新增 insertOrMergeEntity 作業)addInsertOrMergeEntity (adds an insertOrMergeEntity operation)
  • addDeleteEntity (新增 deleteEntity 作業)addDeleteEntity (adds a deleteEntity operation)

下列範例示範如何以單一要求執行 insertEntitydeleteEntity 作業。The following example shows how to execute insertEntity and deleteEntity operations in a single request.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\EdmType;
use MicrosoftAzure\Storage\Table\Models\BatchOperations;

// Configure a connection string for Storage Table service.
$connectionString = "DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]"

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

// Create list of batch operation.
$operations = new BatchOperations();

$entity1 = new Entity();
$entity1->setPartitionKey("tasksSeattle");
$entity1->setRowKey("2");
$entity1->addProperty("Description", null, "Clean roof gutters.");
$entity1->addProperty("DueDate",
                        EdmType::DATETIME,
                        new DateTime("2012-11-05T08:15:00-08:00"));
$entity1->addProperty("Location", EdmType::STRING, "Home");

// Add operation to list of batch operations.
$operations->addInsertEntity("mytable", $entity1);

// Add operation to list of batch operations.
$operations->addDeleteEntity("mytable", "tasksSeattle", "1");

try    {
    $tableClient->batch($operations);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

如需有關批次處理資料表作業的詳細資訊,請參閱執行實體群組交易For more information about batching Table operations, see Performing Entity Group Transactions.

刪除資料表Delete a table

最後,若要刪除資料表,請將資料表名稱傳遞給 TableRestProxy->deleteTable 方法。Finally, to delete a table, pass the table name to the TableRestProxy->deleteTable method.

require_once 'vendor/autoload.php';

use MicrosoftAzure\Storage\Table\TableRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

// Create table REST proxy.
$tableClient = TableRestProxy::createTableService($connectionString);

try    {
    // Delete table.
    $tableClient->deleteTable("mytable");
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here:
    // https://docs.microsoft.com/rest/api/storageservices/Table-Service-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

後續步驟Next steps

了解 Azure 表格服務和 Azure Cosmos DB 的基礎概念之後,請依循下列連結以深入了解。Now that you've learned the basics of the Azure Table service and Azure Cosmos DB, follow these links to learn more.