

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 를 사용한 Amazon DynamoDB 예제 AWS SDK for C\$1\$1
<a name="examples-dynamodb"></a>

Amazon DynamoDB는 완전관리형 NoSQL 데이터베이스 서비스로서 원활한 확장성과 함께 빠르고 예측 가능한 성능을 제공합니다. 다음 예제에서는 AWS SDK for C\$1\$1를 사용하여 [Amazon DynamoDB](https://aws.amazon.com/dynamodb)를 프로그래밍하는 방법을 보여줍니다.

**참고**  
이 안내서에는 특정 기술을 시연하는 데 필요한 코드만 제공되며 [전체 예제 코드는 GitHub에서 확인할 수 있습니다](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp). GitHub에서 단일 소스 파일을 다운로드하거나, 리포지토리를 로컬에 복제하여 모든 예제를 가져오고 빌드하고 실행할 수 있습니다.

**Topics**
+ [DynamoDB에서 테이블 작업](examples-dynamodb-tables.md)
+ [DynamoDB에서 항목 작업](examples-dynamodb-items.md)

# DynamoDB에서 테이블 작업
<a name="examples-dynamodb-tables"></a>

테이블은 DynamoDB 데이터베이스 내 모든 항목을 위한 컨테이너입니다. DynamoDB에 데이터를 추가하거나 제거하기 전에 테이블을 생성해야 합니다.

각 테이블마다 다음을 정의해야 합니다.
+  AWS 계정 및에 고유한 테이블 *이름*입니다 AWS 리전.
+ *프라이머리 키*(모든 값이 고유해야 함). 테이블 내 두 항목은 동일한 프라이머리 키 값을 사용할 수 없습니다.

  기본 키는 단일 파티션(HASH) 키로 이루어진 *단순형*이거나, 파티션과 정렬(RANGE) 키로 이루어진 *복합형*일 수 있습니다.

  각 키 값에는 [ScalarAttributeType](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/namespace_aws_1_1_dynamo_d_b_1_1_model.html#a4b39ae66214e022d3737079d071e4bcb.html) 클래스에 의해 열거되는 관련 *데이터 유형*이 있습니다. 키 값은 이진(B), 숫자(N) 또는 문자열(S)일 수 있습니다. 자세한 내용은 Amazon DynamoDB 개발자 안내서에서 [이름 지정 규칙 및 데이터 형식](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html)을 참조하세요.
+  테이블에 대해 예약된 읽기/쓰기 용량 단위를 정의하는 *프로비저닝된 처리량*
**참고**  
 [Amazon DynamoDB 요금](https://aws.amazon.com/dynamodb/pricing/)은 테이블에 대해 설정하는 프로비저닝된 처리량 값을 기준으로 하므로 테이블에 대해 필요한 만큼의 용량만 예약하십시오.  
언제라도 테이블의 프로비저닝된 처리량을 수정할 수 있으므로 변경이 필요할 경우 용량을 조정할 수 있습니다.

## 표 생성
<a name="dynamodb-create-table"></a>

새 DynamoDB 테이블을 생성하려면 [DynamoDB 클라이언트](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)의 `CreateTable` 메서드를 사용합니다. 테이블 속성과 테이블 스키마를 구성해야 하며, 이 두 가지 요소 모두 테이블의 기본 키를 식별하는 데 사용됩니다. 초기 프로비저닝 처리량 값과 테이블 이름을 제공해야 합니다. `CreateTable`은 비동기식 작업입니다. 테이블이 ACTIVE 상태가 되어 사용 준비가 될 때까지 `GetTableStatus`는 CREATING 상태를 반환합니다.

### 단순형 기본 키를 사용하여 테이블 생성
<a name="dynamodb-create-table-simple"></a>

이 코드는 단순형 기본 키("Name")를 사용하여 테이블을 만듭니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>
```

 **코드** 

```
//! Create an Amazon DynamoDB table.
/*!
  \sa createTable()
  \param tableName: Name for the DynamoDB table.
  \param primaryKey: Primary key for the DynamoDB table.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTable(const Aws::String &tableName,
                                   const Aws::String &primaryKey,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a simple primary key: \"" << primaryKey << "\"." << std::endl;

    Aws::DynamoDB::Model::CreateTableRequest request;

    Aws::DynamoDB::Model::AttributeDefinition hashKey;
    hashKey.SetAttributeName(primaryKey);
    hashKey.SetAttributeType(Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement;
    keySchemaElement.WithAttributeName(primaryKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement);

    Aws::DynamoDB::Model::ProvisionedThroughput throughput;
    throughput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
    request.SetProvisionedThroughput(throughput);
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::CreateTableOutcome &outcome = dynamoClient.CreateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Table \""
                  << outcome.GetResult().GetTableDescription().GetTableName() <<
                  " created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table: " << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table.cpp)를 참조하세요.

### 복합형 기본 키를 사용하여 테이블 생성
<a name="dynamodb-create-table-composite"></a>

다른 [AttributeDefinition](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_definition.html) 및 [KeySchemaElement](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_key_schema_element.html)를 [CreateTableRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_create_table_request.html)에 추가합니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>
```

 **코드** 

```
//! Create an Amazon DynamoDB table with a composite key.
/*!
  \sa createTableWithCompositeKey()
  \param tableName: Name for the DynamoDB table.
  \param partitionKey: Name for the partition (hash) key.
  \param sortKey: Name for the sort (range) key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTableWithCompositeKey(const Aws::String &tableName,
                                                   const Aws::String &partitionKey,
                                                   const Aws::String &sortKey,
                                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a composite primary key:\n" \
            "* " << partitionKey << " - partition key\n" \
            "* " << sortKey << " - sort key\n";

    Aws::DynamoDB::Model::CreateTableRequest request;

    Aws::DynamoDB::Model::AttributeDefinition hashKey1, hashKey2;
    hashKey1.WithAttributeName(partitionKey).WithAttributeType(
            Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey1);
    hashKey2.WithAttributeName(sortKey).WithAttributeType(
            Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey2);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement1, keySchemaElement2;
    keySchemaElement1.WithAttributeName(partitionKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement1);
    keySchemaElement2.WithAttributeName(sortKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::RANGE);
    request.AddKeySchema(keySchemaElement2);

    Aws::DynamoDB::Model::ProvisionedThroughput throughput;
    throughput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
    request.SetProvisionedThroughput(throughput);

    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::CreateTableOutcome &outcome = dynamoClient.CreateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Table \""
                  << outcome.GetResult().GetTableDescription().GetTableName() <<
                  "\" was created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table:" << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

GitHub의 [전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table_composite_key.cpp)를 참조하세요.

## 테이블 나열
<a name="dynamodb-list-tables"></a>

[DynamoDB 클라이언트](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)의 `ListTables` 메서드를 직접적으로 호출하면 특정 리전의 테이블을 나열할 수 있습니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ListTablesRequest.h>
#include <aws/dynamodb/model/ListTablesResult.h>
#include <iostream>
```

 **코드** 

```
//! List the Amazon DynamoDB tables for the current AWS account.
/*!
  \sa listTables()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::listTables(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::ListTablesRequest listTablesRequest;
    listTablesRequest.SetLimit(50);
    do {
        const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamoClient.ListTables(
                listTablesRequest);
        if (!outcome.IsSuccess()) {
            std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        for (const auto &tableName: outcome.GetResult().GetTableNames())
            std::cout << tableName << std::endl;
        listTablesRequest.SetExclusiveStartTableName(
                outcome.GetResult().GetLastEvaluatedTableName());

    } while (!listTablesRequest.GetExclusiveStartTableName().empty());

    return true;
}
```

기본적으로 호출당 최대 100개의 테이블이 반환됩니다. 반환된 [ListTablesOutcome](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html) 객체에 `GetExclusiveStartTableName`을 사용하면 마지막으로 평가된 테이블을 가져올 수 있습니다. 이 값을 사용하여 이전 목록의 마지막으로 반환된 값 다음에 이어지는 목록을 시작할 수 있습니다.

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/list_tables.cpp)를 참조하세요.

## 테이블 정보 검색
<a name="dynamodb-describe-table"></a>

테이블에 대한 자세한 정보는 [DynamoDB 클라이언트](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)의 `DescribeTable` 메서드를 직접적으로 호출하여 확인할 수 있습니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/DescribeTableRequest.h>
#include <iostream>
```

 **코드** 

```
//! Describe an Amazon DynamoDB table.
/*!
  \sa describeTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::describeTable(const Aws::String &tableName,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DescribeTableOutcome &outcome = dynamoClient.DescribeTable(
            request);

    if (outcome.IsSuccess()) {
        const Aws::DynamoDB::Model::TableDescription &td = outcome.GetResult().GetTable();
        std::cout << "Table name  : " << td.GetTableName() << std::endl;
        std::cout << "Table ARN   : " << td.GetTableArn() << std::endl;
        std::cout << "Status      : "
                  << Aws::DynamoDB::Model::TableStatusMapper::GetNameForTableStatus(
                          td.GetTableStatus()) << std::endl;
        std::cout << "Item count  : " << td.GetItemCount() << std::endl;
        std::cout << "Size (bytes): " << td.GetTableSizeBytes() << std::endl;

        const Aws::DynamoDB::Model::ProvisionedThroughputDescription &ptd = td.GetProvisionedThroughput();
        std::cout << "Throughput" << std::endl;
        std::cout << "  Read Capacity : " << ptd.GetReadCapacityUnits() << std::endl;
        std::cout << "  Write Capacity: " << ptd.GetWriteCapacityUnits() << std::endl;

        const Aws::Vector<Aws::DynamoDB::Model::AttributeDefinition> &ad = td.GetAttributeDefinitions();
        std::cout << "Attributes" << std::endl;
        for (const auto &a: ad)
            std::cout << "  " << a.GetAttributeName() << " (" <<
                      Aws::DynamoDB::Model::ScalarAttributeTypeMapper::GetNameForScalarAttributeType(
                              a.GetAttributeType()) <<
                      ")" << std::endl;
    }
    else {
        std::cerr << "Failed to describe table: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```

GitHub의 [전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/describe_table.cpp)를 참조하세요.

## 테이블 수정
<a name="dynamodb-update-table"></a>

[DynamoDB 클라이언트](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)의 `UpdateTable` 메서드를 직접적으로 호출하면 테이블의 프로비저닝 처리량 값을 언제든지 수정할 수 있습니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/UpdateTableRequest.h>
#include <iostream>
```

 **코드** 

```
//! Update a DynamoDB table.
/*!
  \sa updateTable()
  \param tableName: Name for the DynamoDB table.
  \param readCapacity: Provisioned read capacity.
  \param writeCapacity: Provisioned write capacity.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::updateTable(const Aws::String &tableName,
                                   long long readCapacity, long long writeCapacity,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Updating " << tableName << " with new provisioned throughput values"
              << std::endl;
    std::cout << "Read capacity : " << readCapacity << std::endl;
    std::cout << "Write capacity: " << writeCapacity << std::endl;

    Aws::DynamoDB::Model::UpdateTableRequest request;
    Aws::DynamoDB::Model::ProvisionedThroughput provisionedThroughput;
    provisionedThroughput.WithReadCapacityUnits(readCapacity).WithWriteCapacityUnits(
            writeCapacity);
    request.WithProvisionedThroughput(provisionedThroughput).WithTableName(tableName);

    const Aws::DynamoDB::Model::UpdateTableOutcome &outcome = dynamoClient.UpdateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated the table." << std::endl;
    } else {
        const Aws::DynamoDB::DynamoDBError &error = outcome.GetError();
        if (error.GetErrorType() == Aws::DynamoDB::DynamoDBErrors::VALIDATION &&
            error.GetMessage().find("The provisioned throughput for the table will not change") != std::string::npos) {
            std::cout << "The provisioned throughput for the table will not change." << std::endl;
        } else {
            std::cerr << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return waitTableActive(tableName, dynamoClient);
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/update_table.cpp)를 참조하세요.

## 테이블 삭제
<a name="dynamodb-delete-table"></a>

[DynamoDB 클라이언트](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)의 `DeleteTable` 메서드를 직접적으로 호출하고 테이블 이름을 이 메서드에 전달합니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/DeleteTableRequest.h>
#include <iostream>
```

 **코드** 

```
//! Delete an Amazon DynamoDB table.
/*!
  \sa deleteTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteTable(const Aws::String &tableName,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}
```

GitHub의 [전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/delete_table.cpp)를 참조하세요.

## 추가 정보
<a name="more-info"></a>
+  Amazon DynamoDB 개발자 안내서의 [테이블 작업 가이드라인](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html)
+  Amazon DynamoDB 개발자 안내서의 [DynamoDB에서 테이블 작업](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html)

# DynamoDB에서 항목 작업
<a name="examples-dynamodb-items"></a>

DynamoDB에서 항목은 각각 *이름*과 *값*을 갖는 *속성* 모음입니다. 속성 값은 스칼라, 세트 또는 문서 유형일 수 있습니다. 자세한 내용은 Amazon DynamoDB 개발자 안내서에서 [이름 지정 규칙 및 데이터 형식](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html)을 참조하세요.

## 테이블에서 항목 가져오기
<a name="dynamodb-get-item"></a>

[DynamoDB 클라이언트](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)의 `GetItem` 메서드를 직접적으로 호출합니다. 테이블 이름과 원하는 항목의 프라이머리 키 값이 포함된 [GetItemRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_get_item_request.html) 객체를 전달합니다. 이 메서드는 [GetItemResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_get_item_result.html) 객체를 반환합니다.

반환된 `GetItemResult` 객체의 `GetItem()` 메서드를 사용하여 해당 항목과 연관된 키 `Aws::String`과 값 [AttributeValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_value.html) 페어로 구성된 `Aws::Map`을 가져올 수 있습니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/GetItemRequest.h>
#include <iostream>
```

 **코드** 

```
//! Get an item from an Amazon DynamoDB table.
/*!
  \sa getItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::getItem(const Aws::String &tableName,
                               const Aws::String &partitionKey,
                               const Aws::String &partitionValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::GetItemRequest request;

    // Set up the request.
    request.SetTableName(tableName);
    request.AddKey(partitionKey,
                   Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue));

    // Retrieve the item's fields and values.
    const Aws::DynamoDB::Model::GetItemOutcome &outcome = dynamoClient.GetItem(request);
    if (outcome.IsSuccess()) {
        // Reference the retrieved fields/values.
        const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = outcome.GetResult().GetItem();
        if (!item.empty()) {
            // Output each retrieved field and its value.
            for (const auto &i: item)
                std::cout << "Values: " << i.first << ": " << i.second.GetS()
                          << std::endl;
        }
        else {
            std::cout << "No item found with the key " << partitionKey << std::endl;
        }
    }
    else {
        std::cerr << "Failed to get item: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```

GitHub의 [전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/get_item.cpp)를 참조하세요.

## 테이블에 항목 추가
<a name="dynamodb-add-item"></a>

각 항목을 나타내는 키 `Aws::String` 및 값 [AttributeValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_value.html) 페어를 생성합니다. 여기에는 테이블의 기본 키 필드 값이 포함되어야 합니다. 기본 키로 식별되는 항목이 이미 존재하면 필드가 요청에 따라 *업데이트됩니다*. `AddItem` 메서드를 사용하여 [PutItemRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_put_item_request.html)에 추가합니다.

 **포함 파일** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/PutItemRequest.h>
#include <aws/dynamodb/model/PutItemResult.h>
#include <iostream>
```

 **코드** 

```
//! Put an item in an Amazon DynamoDB table.
/*!
  \sa putItem()
  \param tableName: The table name.
  \param artistKey: The artist key. This is the partition key for the table.
  \param artistValue: The artist value.
  \param albumTitleKey: The album title key.
  \param albumTitleValue: The album title value.
  \param awardsKey: The awards key.
  \param awardsValue: The awards value.
  \param songTitleKey: The song title key.
  \param songTitleValue: The song title value.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::putItem(const Aws::String &tableName,
                               const Aws::String &artistKey,
                               const Aws::String &artistValue,
                               const Aws::String &albumTitleKey,
                               const Aws::String &albumTitleValue,
                               const Aws::String &awardsKey,
                               const Aws::String &awardsValue,
                               const Aws::String &songTitleKey,
                               const Aws::String &songTitleValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::PutItemRequest putItemRequest;
    putItemRequest.SetTableName(tableName);

    putItemRequest.AddItem(artistKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            artistValue)); // This is the hash key.
    putItemRequest.AddItem(albumTitleKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            albumTitleValue));
    putItemRequest.AddItem(awardsKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(awardsValue));
    putItemRequest.AddItem(songTitleKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(songTitleValue));

    const Aws::DynamoDB::Model::PutItemOutcome outcome = dynamoClient.PutItem(
            putItemRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully added Item!" << std::endl;
    }
    else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

GitHub의 [전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/put_item.cpp)를 참조하세요.

## 테이블의 기존 항목 업데이트
<a name="dynamodb-update-item"></a>

테이블에 이미 존재하는 항목의 속성을 업데이트하려면 DynamoDBClient의 `UpdateItem` 메서드를 사용합니다. 이때 테이블 이름, 프라이머리 키 값, 업데이트할 필드 및 해당 값을 제공해야 합니다.

 **가져오기** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/UpdateItemRequest.h>
#include <aws/dynamodb/model/UpdateItemResult.h>
#include <iostream>
```

 **코드** 

```
//! Update an Amazon DynamoDB table item.
/*!
  \sa updateItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param attributeKey: The key for the attribute to be updated.
  \param attributeValue: The value for the attribute to be updated.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 *  The example code only sets/updates an attribute value. It processes
 *  the attribute value as a string, even if the value could be interpreted
 *  as a number. Also, the example code does not remove an existing attribute
 *  from the key value.
 */

bool AwsDoc::DynamoDB::updateItem(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &attributeKey,
                                  const Aws::String &attributeValue,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // *** Define UpdateItem request arguments.
    // Define TableName argument.
    Aws::DynamoDB::Model::UpdateItemRequest request;
    request.SetTableName(tableName);

    // Define KeyName argument.
    Aws::DynamoDB::Model::AttributeValue attribValue;
    attribValue.SetS(partitionValue);
    request.AddKey(partitionKey, attribValue);

    // Construct the SET update expression argument.
    Aws::String update_expression("SET #a = :valueA");
    request.SetUpdateExpression(update_expression);

    // Construct attribute name argument.
    Aws::Map<Aws::String, Aws::String> expressionAttributeNames;
    expressionAttributeNames["#a"] = attributeKey;
    request.SetExpressionAttributeNames(expressionAttributeNames);

    // Construct attribute value argument.
    Aws::DynamoDB::Model::AttributeValue attributeUpdatedValue;
    attributeUpdatedValue.SetS(attributeValue);
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> expressionAttributeValues;
    expressionAttributeValues[":valueA"] = attributeUpdatedValue;
    request.SetExpressionAttributeValues(expressionAttributeValues);

    // Update the item.
    const Aws::DynamoDB::Model::UpdateItemOutcome &outcome = dynamoClient.UpdateItem(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Item was updated" << std::endl;
    } else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/update_item.cpp)를 참조하세요.

## 추가 정보
<a name="more-info"></a>
+  Amazon DynamoDB 개발자 안내서의 [항목 작업 지침](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForItems.html)
+  Amazon DynamoDB 개발자 안내서의 [DynamoDB에서 항목 작업](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html)