Accessing Azure Storage Tables

This article describes how to access and manipulate data in Azure Table Storage, a NoSQL key-attribute store available as part of the Azure Storage suite. We'll cover common methods using the Azure SDKs and the REST API.

Prerequisites

Accessing Tables with Azure SDKs

Azure provides client libraries (SDKs) for various programming languages to simplify interaction with Table Storage. Below are examples using C# and Python.

C# Example

First, ensure you have the Azure.Data.Tables NuGet package installed.


using Azure;
using Azure.Data.Tables;
using System;
using System.Threading.Tasks;

public class TableAccessExample
{
    public static async Task Main(string[] args)
    {
        string connectionString = "YOUR_STORAGE_CONNECTION_STRING";
        string tableName = "MySampleTable";

        TableClient tableClient = new TableClient(connectionString, tableName);

        // Create the table if it doesn't exist
        await tableClient.CreateIfNotExistsAsync();
        Console.WriteLine($"Table '{tableName}' ensured.");

        // Example entity
        var customer = new MyEntity("Contoso", "Smith")
        {
            Email = "walter@contoso.com",
            PhoneNumber = "555-1234"
        };

        // Add an entity
        await tableClient.UpsertEntityAsync(customer);
        Console.WriteLine($"Entity added/updated: {customer.RowKey}");

        // Retrieve an entity
        Response<MyEntity> retrievedCustomer = await tableClient.GetEntityAsync<MyEntity>("Contoso", "Smith");
        Console.WriteLine($"Retrieved Entity: {retrievedCustomer.Value.PartitionKey}, {retrievedCustomer.Value.RowKey}, {retrievedCustomer.Value.Email}");
    }
}

// Define your entity class
public class MyEntity : ITableEntity
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }

    public string Email { get; set; }
    public string PhoneNumber { get; set; }

    public MyEntity(string partitionKey, string rowKey)
    {
        PartitionKey = partitionKey;
        RowKey = rowKey;
    }

    // Default constructor for deserialization
    public MyEntity() { }
}
            

Python Example

Install the Azure Tables SDK: pip install azure-data-tables


from azure.data.tables import TableServiceClient
from azure.core.exceptions import ResourceExistsError

CONNECTION_STRING = "YOUR_STORAGE_CONNECTION_STRING"
TABLE_NAME = "MySampleTablePython"

def main():
    table_service_client = TableServiceClient.from_connection_string(conn_str=CONNECTION_STRING)

    try:
        table_client = table_service_client.create_table(TABLE_NAME)
        print(f"Table '{TABLE_NAME}' created.")
    except ResourceExistsError:
        table_client = table_service_client.get_table_client(TABLE_NAME)
        print(f"Table '{TABLE_NAME}' already exists.")

    # Example entity
    entity = {
        "PartitionKey": "Contoso",
        "RowKey": "Smith",
        "Email": "walter@contoso.com",
        "PhoneNumber": "555-1234"
    }

    # Add an entity
    try:
        table_client.upsert_entity(entity)
        print(f"Entity added/updated: {entity['PartitionKey']}, {entity['RowKey']}")
    except Exception as e:
        print(f"Error adding/updating entity: {e}")

    # Retrieve an entity
    try:
        retrieved_entity = table_client.get_entity("Contoso", "Smith")
        print(f"Retrieved Entity: {retrieved_entity['PartitionKey']}, {retrieved_entity['RowKey']}, {retrieved_entity.get('Email')}")
    except Exception as e:
        print(f"Error retrieving entity: {e}")

if __name__ == "__main__":
    main()
            

Accessing Tables with the REST API

You can also interact with Azure Table Storage directly using its REST API. This involves making HTTP requests to the appropriate endpoints.

Key Operations:

Requests to the REST API are authenticated using Shared Key or Shared Access Signatures (SAS).

Important Considerations

When designing your tables, consider the partition key and row key carefully. These keys are crucial for performance and scalability. Choose partition keys that distribute your data evenly across partitions to avoid hot spots.

Security Best Practices

Never embed connection strings directly in client-side code. Use secure methods like Azure Key Vault or environment variables to manage credentials.

Next Steps