使用 Amazon SDK 在 DynamoDB 表中放置项目 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon SDK 在 DynamoDB 表中放置项目

以下代码示例显示如何将项目放入 DynamoDB 表中。

.NET
Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅 GitHub

/// <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 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 PutItem

C++
适用于 C++ 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::PutItemRequest putItemRequest; putItemRequest.SetTableName(table); Aws::DynamoDB::Model::AttributeValue av; av.SetS(keyVal); Aws::DynamoDB::Model::AttributeValue album; album.SetS(AlbumTitleValue); Aws::DynamoDB::Model::AttributeValue awards; awards.SetS(AwardVal); Aws::DynamoDB::Model::AttributeValue song; song.SetS(SongTitleVal); // Add all AttributeValue objects. putItemRequest.AddItem(key, av); putItemRequest.AddItem(albumTitle, album); putItemRequest.AddItem(Awards, awards); putItemRequest.AddItem(SongTitle, song); const Aws::DynamoDB::Model::PutItemOutcome result = dynamoClient.PutItem(putItemRequest); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; return 1; } std::cout << "Successfully added Item!" << std::endl;
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 PutItem

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

// 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 详细信息,请参阅《Amazon SDK for Go API 参考》中的 PutItem

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅 GitHub

使用增强型客户端将项目放入表中。

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("id119"); 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."); }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 PutItem

JavaScript
SDK for JavaScript V3
提示

要了解如何设置和运行此示例,请参阅 GitHub

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". 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: false, // 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. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); 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 { const data = 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 { const data = 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 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 PutItem

SDK for JavaScript V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

将项目放入表中。

// 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
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

提示

要了解如何设置和运行此示例,请参阅 GitHub

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 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 PutItem

Python
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

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 (Boto3) 的 Amazon SDK API 参考》中的 PutItem

Ruby
SDK for Ruby
提示

要了解如何设置和运行此示例,请参阅 GitHub

# 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 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 PutItem

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

提示

要了解如何设置和运行此示例,请参阅 GitHub

async fn add_item( client: &Client, table: &str, username: &str, p_type: &str, age: &str, first: &str, last: &str, ) -> Result<(), Error> { let user_av = AttributeValue::S(username.into()); let type_av = AttributeValue::S(p_type.into()); let age_av = AttributeValue::S(age.into()); let first_av = AttributeValue::S(first.into()); let last_av = AttributeValue::S(last.into()); 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 [{:?}] to add item...", request); request.send().await?; println!( "Added user {}, {} {}, age {} as {} user", username, first, last, age, p_type ); Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 PutItem

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 结合使用 DynamoDB 与 Amazon SDK。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。