将项目写入 DynamoDB 表中
您可以使用 Amazon Web Services Management Console、Amazon CLI 或 Amazon SDK 向 DynamoDB 表中写入项目。有关项目的更多信息,请参阅 Amazon DynamoDB 的核心组件。
使用 Amazon SDK 向 DynamoDB 表中写入项目
以下代码示例显示如何使用 Amazon SDK 向 DynamoDB 表中写入项目。
- .NET
-
- Amazon SDK for .NET
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 /// <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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 //! 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 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 PutItem。
-
- Go
-
- SDK for Go V2
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 // 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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用增强型客户端将项目放入表中。
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 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 PutItem。
-
- JavaScript
-
- SDK for JavaScript V3
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 创建客户端。
// 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 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 PutItem。
-
- SDK for JavaScript V2
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 将项目放入表中。
// 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); } });
-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 PutItem。
-
- Kotlin
-
- SDK for Kotlin
-
注意 这是适用于预览版中功能的预发行文档。本文档随时可能更改。
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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
。
-
- PHP
-
- SDK for PHP
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 PutItem。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 # 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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 PutItem
。
-
有关更多 DynamoDB 示例,请参阅适用于使用 Amazon SDK 的 DynamoDB 的代码示例。