DynamoDB 테이블에 항목을 씁니다. - Amazon DynamoDB

DynamoDB 테이블에 항목을 씁니다.

AWS Management Console, AWS CLI 또는 AWS SDK를 사용하여 DynamoDB 테이블에 항목을 쓸 수 있습니다. 항목에 대한 자세한 내용은 Amazon DynamoDB의 핵심 구성 요소 섹션을 참조하세요.

AWS SDK를 사용하여 DynamoDB 테이블에 항목 쓰기

다음 코드 예제에서는 AWS SDK를 사용하여 DynamoDB 테이블에 항목을 쓰는 방법을 보여줍니다.

.NET
AWS SDK for .NET
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Adds a new item to the table. /// </summary> /// <param name="client">An initialized Amazon DynamoDB client object.</param> /// <param name="newMovie">A Movie object containing informtation for /// the movie to add to the table.</param> /// <param name="tableName">The name of the table where the item will be added.</param> /// <returns>A Boolean value that indicates the results of adding the item.</returns> public static async Task<bool> PutItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName) { var item = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new PutItemRequest { TableName = tableName, Item = item, }; var response = await client.PutItemAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • API에 대한 세부 정보는 AWS SDK for .NET API 참조PutItem을 참조하세요.

C++
SDK for C++
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

//! 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 outcome.IsSuccess(); }
  • API에 대한 세부 정보는 AWS SDK for C++ API 참조PutItem을 참조하세요.

Go
Go V2용 SDK
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples. // It contains a DynamoDB service client that is used to act on the specified table. type TableBasics struct { DynamoDbClient *dynamodb.Client TableName string } // AddMovie adds a movie the DynamoDB table. func (basics TableBasics) AddMovie(movie Movie) error { item, err := attributevalue.MarshalMap(movie) if err != nil { panic(err) } _, err = basics.DynamoDbClient.PutItem(context.TODO(), &dynamodb.PutItemInput{ TableName: aws.String(basics.TableName), Item: item, }) if err != nil { log.Printf("Couldn't add item to table. Here's why: %v\n", err) } return err }
  • API에 대한 세부 정보는 AWS SDK for Go API 참조PutItem을 참조하세요.

Java
Java 2.x용 SDK
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

고급형 클라이언트를 사용하여 테이블에 항목을 추가합니다.

public static void putRecord(DynamoDbEnhancedClient enhancedClient) { try { DynamoDbTable<Customer> custTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); // Create an Instant value. LocalDate localDate = LocalDate.parse("2020-04-07"); LocalDateTime localDateTime = localDate.atStartOfDay(); Instant instant = localDateTime.toInstant(ZoneOffset.UTC); // Populate the Table. Customer custRecord = new Customer(); custRecord.setCustName("Tom red"); custRecord.setId("id101"); custRecord.setEmail("tred@noserver.com"); custRecord.setRegistrationDate(instant) ; // Put the customer data into an Amazon DynamoDB table. custTable.putItem(custRecord); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Customer data added to the table with id id101"); }
  • API에 대한 세부 정보는 AWS SDK for Java 2.x API 참조PutItem을 참조하세요.

JavaScript
JavaScript V3용 SDK
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

클라이언트를 생성합니다.

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DEFAULT_REGION } from "../../../../libs/utils/util-aws-sdk.js"; // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: DEFAULT_REGION });

DynamoDB 문서 클라이언트를 생성합니다.

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: true, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, { marshallOptions, unmarshallOptions, }); export { ddbDocClient };

DynamoDB 문서 클라이언트를 사용하여 테이블에 항목을 추가합니다.

import { PutCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; export const putItem = async () => { // Set the parameters. export const params = { TableName: "TABLE_NAME", Item: { primaryKey: "VALUE_1", sortKey: "VALUE_2", }, }; try { const data = await ddbDocClient.send(new PutCommand(params)); console.log("Success - item added or updated", data); } catch (err) { console.log("Error", err.stack); } }; putItem();

PartiQL을 사용하여 테이블에 항목을 추가합니다.

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; export const run = async (tableName, movieTitle1, movieYear1) => { const params = { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; try { await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item added."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieTitle1, movieYear1);

PartiQL을 사용하여 배치로 테이블에 항목을 추가합니다.

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { const params = { Statements: [ { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items added."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);
  • API에 대한 세부 정보는 AWS SDK for JavaScript API 참조PutItem을 참조하세요.

JavaScript V2용 SDK
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

테이블에 항목을 추가합니다.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); var params = { TableName: 'CUSTOMER_LIST', Item: { 'CUSTOMER_ID' : {N: '001'}, 'CUSTOMER_NAME' : {S: 'Richard Roe'} } }; // Call DynamoDB to add the item to the table ddb.putItem(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

DynamoDB 문서 클라이언트를 사용하여 테이블에 항목을 추가합니다.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); var params = { TableName: 'TABLE', Item: { 'HASHKEY': VALUE, 'ATTRIBUTE_1': 'STRING_VALUE', 'ATTRIBUTE_2': VALUE_2 } }; docClient.put(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Kotlin
Kotlin용 SDK
참고

이 시험판 설명서는 미리 보기 버전 기능에 관한 것입니다. 변경될 수 있습니다.

참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

suspend fun putItemInTable( tableNameVal: String, key: String, keyVal: String, albumTitle: String, albumTitleValue: String, awards: String, awardVal: String, songTitle: String, songTitleVal: String ) { val itemValues = mutableMapOf<String, AttributeValue>() // Add all content to the table. itemValues[key] = AttributeValue.S(keyVal) itemValues[songTitle] = AttributeValue.S(songTitleVal) itemValues[albumTitle] = AttributeValue.S(albumTitleValue) itemValues[awards] = AttributeValue.S(awardVal) val request = PutItemRequest { tableName = tableNameVal item = itemValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.putItem(request) println(" A new item was placed into $tableNameVal.") } }
  • API에 대한 세부 정보는 Kotlin용 AWS SDK API 참조PutItem을 참조하세요.

PHP
PHP용 SDK
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $service->putItem([ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], 'TableName' => $tableName, ]); public function putItem(array $array) { $this->dynamoDbClient->putItem($array); }
  • API에 대한 세부 정보는 AWS SDK for PHP API 참조PutItem을 참조하세요.

Python
Python용 SDK(Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

class Movies: """Encapsulates an Amazon DynamoDB table of movie data.""" def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource self.table = None def add_movie(self, title, year, plot, rating): """ Adds a movie to the table. :param title: The title of the movie. :param year: The release year of the movie. :param plot: The plot summary of the movie. :param rating: The quality rating of the movie. """ try: self.table.put_item( Item={ 'year': year, 'title': title, 'info': {'plot': plot, 'rating': Decimal(str(rating))}}) except ClientError as err: logger.error( "Couldn't add movie %s to table %s. Here's why: %s: %s", title, self.table.name, err.response['Error']['Code'], err.response['Error']['Message']) raise
  • API 세부 정보는 Python용 AWS SDK(Boto3) API 참조PutItem을 참조하세요.

Ruby
Ruby용 SDK
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

# Adds a movie to the table. # # @param title [String] The title of the movie. # @param year [Integer] The release year of the movie. # @param plot [String] The plot summary of the movie. # @param rating [Float] The quality rating of the movie. def add_movie(title:, year:, plot:, rating:) @table.put_item( item: { "year" => year, "title" => title, "info" => {"plot" => plot, "rating" => rating}}) rescue Aws::Errors::ServiceError => e puts("Couldn't add movie #{title} to table #{@table.name}. Here's why:") puts("\t#{e.code}: #{e.message}") raise end
  • API에 대한 세부 정보는 AWS SDK for Ruby API 참조PutItem을 참조하세요.

Rust
Rust용 SDK
참고

이 설명서는 평가판 버전 SDK에 관한 것입니다. SDK는 변경될 수 있으며 프로덕션에서 사용해서는 안 됩니다.

참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

pub async fn add_item(client: &Client, item: Item, table: &String) -> Result<ItemOut, Error> { let user_av = AttributeValue::S(item.username); let type_av = AttributeValue::S(item.p_type); let age_av = AttributeValue::S(item.age); let first_av = AttributeValue::S(item.first); let last_av = AttributeValue::S(item.last); let request = client .put_item() .table_name(table) .item("username", user_av) .item("account_type", type_av) .item("age", age_av) .item("first_name", first_av) .item("last_name", last_av); println!("Executing request [{request:?}] to add item..."); let resp = request.send().await?; let attributes = resp.attributes().unwrap(); let username = attributes.get("username").cloned(); let first_name = attributes.get("first_name").cloned(); let last_name = attributes.get("last_name").cloned(); let age = attributes.get("age").cloned(); let p_type = attributes.get("p_type").cloned(); println!( "Added user {:?}, {:?} {:?}, age {:?} as {:?} user", username, first_name, last_name, age, p_type ); Ok(ItemOut { p_type, age, username, first_name, last_name, }) }
  • API에 대한 세부 정보는 Rust용 AWS SDK API 참조PutItem을 참조하세요.

더 많은 DynamoDB 예제는 AWS SDK를 사용한 DynamoDB용 코드 예제 섹션을 참조하세요.