Étape 2 : Écrire des données dans une table - Amazon DynamoDB

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Étape 2 : Écrire des données dans une table

Dans cette étape, vous insérez plusieurs éléments dans la table Music que vous avez créée dans Étape 1 : créer une table.

Pour plus d'informations sur les opérations d'écriture, consultez Écriture d'un élément.

Suivez ces étapes pour écrire des données sur la table Music à l'aide de la console DynamoDB.

  1. Ouvrez la console DynamoDB à l'adresse. https://console.aws.amazon.com/dynamodb/

  2. Dans le volet de navigation de gauche, choisissez Tables.

  3. Sur la page Tables, choisissez la table musicale.

  4. Sélectionnez Explore table items (Explorer les éléments de la table).

  5. Dans la section Articles retournés, choisissez Créer un article.

  6. Sur la page Créer un article, procédez comme suit pour ajouter des éléments à votre tableau :

    1. Choisissez Ajouter un nouvel attribut, puis choisissez Numéro.

    2. Dans Nom de l'attribut, entrezAwards.

    3. Répétez cette procédure pour créer un AlbumTitle de type Chaîne.

    4. Saisissez les valeurs suivantes pour votre élément :

      1. Pour Artist (Artiste), saisissez No One You Know.

      2. Pour SongTitle, entrezCall Me Today.

      3. Pour AlbumTitle, entrezSomewhat Famous.

      4. Pour Awards (Récompenses), saisissez 1.

  7. Choisissez Créer un élément.

  8. Répétez cette procédure et créez un autre élément avec les valeurs suivantes :

    1. Pour Artist (Artiste), saisissez Acme Band.

    2. Pour SongTitleentrerHappy Day.

    3. Pour AlbumTitle, entrezSongs About Life.

    4. Pour Awards (Récompenses), saisissez 10.

  9. Effectuez cette opération de nouveau pour créer un autre élément avec le même Artist (Artiste) qu'à l'étape précédente, mais avec des valeurs différentes pour les autres attributs :

    1. Pour Artist (Artiste), saisissez Acme Band.

    2. Pour SongTitleentrerPartiQL Rocks.

    3. Pour AlbumTitle, entrezAnother Album Title.

    4. Pour Awards (Récompenses), saisissez 8.

Procédez comme suit : AWS CLI L'exemple crée plusieurs nouveaux éléments dans le Music tableau. Vous pouvez le faire via API DynamoDB ou partiQLSQL, un langage de requête compatible pour DynamoDB.

DynamoDB API

Linux

aws dynamodb put-item \ --table-name Music \ --item \ '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "1"}}' aws dynamodb put-item \ --table-name Music \ --item \ '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Howdy"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "2"}}' aws dynamodb put-item \ --table-name Music \ --item \ '{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}, "AlbumTitle": {"S": "Songs About Life"}, "Awards": {"N": "10"}}' aws dynamodb put-item \ --table-name Music \ --item \ '{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "PartiQL Rocks"}, "AlbumTitle": {"S": "Another Album Title"}, "Awards": {"N": "8"}}'

Fenêtres CMD

aws dynamodb put-item ^ --table-name Music ^ --item ^ "{\"Artist\": {\"S\": \"No One You Know\"}, \"SongTitle\": {\"S\": \"Call Me Today\"}, \"AlbumTitle\": {\"S\": \"Somewhat Famous\"}, \"Awards\": {\"N\": \"1\"}}" aws dynamodb put-item ^ --table-name Music ^ --item ^ "{\"Artist\": {\"S\": \"No One You Know\"}, \"SongTitle\": {\"S\": \"Howdy\"}, \"AlbumTitle\": {\"S\": \"Somewhat Famous\"}, \"Awards\": {\"N\": \"2\"}}" aws dynamodb put-item ^ --table-name Music ^ --item ^ "{\"Artist\": {\"S\": \"Acme Band\"}, \"SongTitle\": {\"S\": \"Happy Day\"}, \"AlbumTitle\": {\"S\": \"Songs About Life\"}, \"Awards\": {\"N\": \"10\"}}" aws dynamodb put-item ^ --table-name Music ^ --item ^ "{\"Artist\": {\"S\": \"Acme Band\"}, \"SongTitle\": {\"S\": \"PartiQL Rocks\"}, \"AlbumTitle\": {\"S\": \"Another Album Title\"}, \"Awards\": {\"N\": \"8\"}}"
PartiQL for DynamoDB

Linux

aws dynamodb execute-statement --statement "INSERT INTO Music \ VALUE \ {'Artist':'No One You Know','SongTitle':'Call Me Today', 'AlbumTitle':'Somewhat Famous', 'Awards':'1'}" aws dynamodb execute-statement --statement "INSERT INTO Music \ VALUE \ {'Artist':'No One You Know','SongTitle':'Howdy', 'AlbumTitle':'Somewhat Famous', 'Awards':'2'}" aws dynamodb execute-statement --statement "INSERT INTO Music \ VALUE \ {'Artist':'Acme Band','SongTitle':'Happy Day', 'AlbumTitle':'Songs About Life', 'Awards':'10'}" aws dynamodb execute-statement --statement "INSERT INTO Music \ VALUE \ {'Artist':'Acme Band','SongTitle':'PartiQL Rocks', 'AlbumTitle':'Another Album Title', 'Awards':'8'}"

Fenêtres CMD

aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'No One You Know','SongTitle':'Call Me Today', 'AlbumTitle':'Somewhat Famous', 'Awards':'1'}" aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'No One You Know','SongTitle':'Howdy', 'AlbumTitle':'Somewhat Famous', 'Awards':'2'}" aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'Acme Band','SongTitle':'Happy Day', 'AlbumTitle':'Songs About Life', 'Awards':'10'}" aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'Acme Band','SongTitle':'PartiQL Rocks', 'AlbumTitle':'Another Album Title', 'Awards':'8'}"

Pour plus d'informations sur l'écriture de données avec PartiQL, veuillez consulter Instructions d'insertion de PartiQL.

Pour plus d'informations sur les types de données pris en charge dans DynamoDB, consultez Types de données.

Pour plus d'informations sur la façon de représenter les types de données DynamoDB JSON dans, consultez la section Valeurs d'attribut.

Les exemples de code suivants montrent comment écrire un élément dans une table DynamoDB à l'aide d'un AWS SDK.

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

/// <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; }
  • Pour API plus de détails, voir PutItemAWS SDK for .NET APIRéférence.

Bash
AWS CLI avec le script Bash
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

############################################################################## # function dynamodb_put_item # # This function puts an item into a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -i item -- Path to json file containing the item values. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################## function dynamodb_put_item() { local table_name item response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_put_item" echo "Put an item into a DynamoDB table." echo " -n table_name -- The name of the table." echo " -i item -- Path to json file containing the item values." echo "" } while getopts "n:i:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; i) item="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$item" ]]; then errecho "ERROR: You must provide an item with the -i parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " item: $item" iecho "" iecho "" response=$(aws dynamodb put-item \ --table-name "$table_name" \ --item file://"$item") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports put-item operation failed.$response" return 1 fi return 0 }

Fonctions utilitaires utilisées dans cet exemple.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • Pour API plus de détails, voir PutItemAWS CLI Référence de commande.

C++
SDKpour C++
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

//! 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(); }
  • Pour API plus de détails, voir PutItemAWS SDK for C++ APIRéférence.

CLI
AWS CLI

Exemple 1 : pour ajouter un élément à un tableau

L'put-itemexemple suivant ajoute un nouvel élément au MusicCollectiontableau.

aws dynamodb put-item \ --table-name MusicCollection \ --item file://item.json \ --return-consumed-capacity TOTAL \ --return-item-collection-metrics SIZE

Contenu de item.json :

{ "Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Greatest Hits"} }

Sortie :

{ "ConsumedCapacity": { "TableName": "MusicCollection", "CapacityUnits": 1.0 }, "ItemCollectionMetrics": { "ItemCollectionKey": { "Artist": { "S": "No One You Know" } }, "SizeEstimateRangeGB": [ 0.0, 1.0 ] } }

Pour plus d'informations, consultez la section Rédaction d'un article dans le guide du développeur Amazon DynamoDB.

Exemple 2 : pour remplacer de manière conditionnelle un élément d'un tableau

L'put-itemexemple suivant remplace un élément existant dans le MusicCollection tableau uniquement si cet élément possède un AlbumTitle attribut dont la valeur est deGreatest Hits. La commande renvoie la valeur précédente de l'élément.

aws dynamodb put-item \ --table-name MusicCollection \ --item file://item.json \ --condition-expression "#A = :A" \ --expression-attribute-names file://names.json \ --expression-attribute-values file://values.json \ --return-values ALL_OLD

Contenu de item.json :

{ "Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"} }

Contenu de names.json :

{ "#A": "AlbumTitle" }

Contenu de values.json :

{ ":A": {"S": "Greatest Hits"} }

Sortie :

{ "Attributes": { "AlbumTitle": { "S": "Greatest Hits" }, "Artist": { "S": "No One You Know" }, "SongTitle": { "S": "Call Me Today" } } }

Si la clé existe déjà, vous devriez voir le résultat suivant :

A client error (ConditionalCheckFailedException) occurred when calling the PutItem operation: The conditional request failed.

Pour plus d'informations, consultez la section Rédaction d'un article dans le guide du développeur Amazon DynamoDB.

  • Pour API plus de détails, voir PutItemAWS CLI Référence de commande.

Go
SDKpour Go V2
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

// 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 } // Movie encapsulates data about a movie. Title and Year are the composite primary key // of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key, // and Info is additional data. type Movie struct { Title string `dynamodbav:"title"` Year int `dynamodbav:"year"` Info map[string]interface{} `dynamodbav:"info"` } // GetKey returns the composite primary key of the movie in a format that can be // sent to DynamoDB. func (movie Movie) GetKey() map[string]types.AttributeValue { title, err := attributevalue.Marshal(movie.Title) if err != nil { panic(err) } year, err := attributevalue.Marshal(movie.Year) if err != nil { panic(err) } return map[string]types.AttributeValue{"title": title, "year": year} } // String returns the title, year, rating, and plot of a movie, formatted for the example. func (movie Movie) String() string { return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n", movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"]) }
  • Pour API plus de détails, voir PutItemAWS SDK for Go APIRéférence.

Java
SDKpour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

Met un élément dans un tableau en utilisant DynamoDbClient.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2, * its better practice to use the * Enhanced Client. See the EnhancedPutItem example. */ public class PutItem { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval> Where: tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3). key - The key used in the Amazon DynamoDB table (for example, Artist). keyval - The key value that represents the item to get (for example, Famous Band). albumTitle - The Album title (for example, AlbumTitle). AlbumTitleValue - The name of the album (for example, Songs About Life ). Awards - The awards column (for example, Awards). AwardVal - The value of the awards (for example, 10). SongTitle - The song title (for example, SongTitle). SongTitleVal - The value of the song title (for example, Happy Day). **Warning** This program will place an item that you specify into a table! """; if (args.length != 9) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; String keyVal = args[2]; String albumTitle = args[3]; String albumTitleValue = args[4]; String awards = args[5]; String awardVal = args[6]; String songTitle = args[7]; String songTitleVal = args[8]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle, songTitleVal); System.out.println("Done!"); ddb.close(); } public static void putItemInTable(DynamoDbClient ddb, String tableName, String key, String keyVal, String albumTitle, String albumTitleValue, String awards, String awardVal, String songTitle, String songTitleVal) { HashMap<String, AttributeValue> itemValues = new HashMap<>(); itemValues.put(key, AttributeValue.builder().s(keyVal).build()); itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build()); itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build()); itemValues.put(awards, AttributeValue.builder().s(awardVal).build()); PutItemRequest request = PutItemRequest.builder() .tableName(tableName) .item(itemValues) .build(); try { PutItemResponse response = ddb.putItem(request); System.out.println(tableName + " was successfully updated. The request id is " + response.responseMetadata().requestId()); } catch (ResourceNotFoundException e) { System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName); System.err.println("Be sure that it exists and that you've typed its name correctly!"); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • Pour API plus de détails, voir PutItemAWS SDK for Java 2.x APIRéférence.

JavaScript
SDKpour JavaScript (v3)
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

Cet exemple utilise le client de document pour simplifier l'utilisation d'éléments dans DynamoDB. Pour API plus de détails, voir PutCommand.

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new PutCommand({ TableName: "HappyAnimals", Item: { CommonName: "Shiba Inu", }, }); const response = await docClient.send(command); console.log(response); return response; };
  • Pour API plus de détails, voir PutItemAWS SDK for JavaScript APIRéférence.

SDKpour JavaScript (v2)
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

Insérez un élément dans la table.

// 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); } });

Insérez un élément dans une table à l'aide du client de document 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
SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

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.") } }
  • Pour API plus de détails, voir PutItemAWS SDKpour API référence à Kotlin.

PHP
SDK pour PHP
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

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); }
  • Pour API plus de détails, voir PutItemAWS SDK for PHP APIRéférence.

PowerShell
Outils pour PowerShell

Exemple 1 : crée un nouvel article ou remplace un article existant par un nouvel article.

$item = @{ SongTitle = 'Somewhere Down The Road' Artist = 'No One You Know' AlbumTitle = 'Somewhat Famous' Price = 1.94 Genre = 'Country' CriticRating = 9.0 } | ConvertTo-DDBItem Set-DDBItem -TableName 'Music' -Item $item
  • Pour API plus de détails, voir PutItemAWS Tools for PowerShell Référence de l'applet de commande.

Python
SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

class Movies: """Encapsulates an Amazon DynamoDB table of movie data. Example data structure for a movie record in this table: { "year": 1999, "title": "For Love of the Game", "info": { "directors": ["Sam Raimi"], "release_date": "1999-09-15T00:00:00Z", "rating": 6.3, "plot": "A washed up pitcher flashes through his career.", "rank": 4987, "running_time_secs": 8220, "actors": [ "Kevin Costner", "Kelly Preston", "John C. Reilly" ] } } """ def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource # The table variable is set during the scenario in the call to # 'exists' if the table exists. Otherwise, it is set by 'create_table'. 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
  • Pour API plus de détails, voir PutItemAWS SDKpour Python (Boto3) Reference. API

Ruby
SDKpour Ruby
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

class DynamoDBBasics attr_reader :dynamo_resource attr_reader :table def initialize(table_name) client = Aws::DynamoDB::Client.new(region: "us-east-1") @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table = @dynamo_resource.table(table_name) end # Adds a movie to the table. # # @param movie [Hash] The title, year, plot, and rating of the movie. def add_item(movie) @table.put_item( item: { "year" => movie[:year], "title" => movie[:title], "info" => {"plot" => movie[:plot], "rating" => movie[:rating]}}) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't add movie #{title} to table #{@table.name}. Here's why:") puts("\t#{e.code}: #{e.message}") raise end
  • Pour API plus de détails, voir PutItemAWS SDK for Ruby APIRéférence.

Rust
SDKpour Rust
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

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, }) }
  • Pour API plus de détails, voir PutItemAWS SDKpour API référence à Rust.

SAP ABAP
SDKpour SAP ABAP
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

TRY. DATA(lo_resp) = lo_dyn->putitem( iv_tablename = iv_table_name it_item = it_item ). MESSAGE '1 row inserted into DynamoDB Table' && iv_table_name TYPE 'I'. CATCH /aws1/cx_dyncondalcheckfaile00. MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'. CATCH /aws1/cx_dynresourcenotfoundex. MESSAGE 'The table or index does not exist' TYPE 'E'. CATCH /aws1/cx_dyntransactconflictex. MESSAGE 'Another transaction is using the item' TYPE 'E'. ENDTRY.
  • Pour API plus de détails, voir PutItemAWS SDKà titre SAP ABAP API de référence.

Swift
SDKpour Swift
Note

Il s'agit de la documentation d'avant-première d'une SDK version préliminaire. Elle est susceptible d’être modifiée.

Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

import AWSDynamoDB /// Add a movie specified as a `Movie` structure to the Amazon DynamoDB /// table. /// /// - Parameter movie: The `Movie` to add to the table. /// func add(movie: Movie) async throws { guard let client = self.ddbClient else { throw MoviesError.UninitializedClient } // Get a DynamoDB item containing the movie data. let item = try await movie.getAsItem() // Send the `PutItem` request to Amazon DynamoDB. let input = PutItemInput( item: item, tableName: self.tableName ) _ = try await client.putItem(input: input) } /// /// Return an array mapping attribute names to Amazon DynamoDB attribute /// values, representing the contents of the `Movie` record as a DynamoDB /// item. /// /// - Returns: The movie item as an array of type /// `[Swift.String:DynamoDBClientTypes.AttributeValue]`. /// func getAsItem() async throws -> [Swift.String:DynamoDBClientTypes.AttributeValue] { // Build the item record, starting with the year and title, which are // always present. var item: [Swift.String:DynamoDBClientTypes.AttributeValue] = [ "year": .n(String(self.year)), "title": .s(self.title) ] // Add the `info` field with the rating and/or plot if they're // available. var details: [Swift.String:DynamoDBClientTypes.AttributeValue] = [:] if (self.info.rating != nil || self.info.plot != nil) { if self.info.rating != nil { details["rating"] = .n(String(self.info.rating!)) } if self.info.plot != nil { details["plot"] = .s(self.info.plot!) } } item["info"] = .m(details) return item }
  • Pour API plus de détails, voir PutItemAWS SDKpour API référence à Swift.

Pour obtenir plus d'exemples avec DynamoDB, consultez Exemples de code pour DynamoDB utilisant AWS SDKs.

Après avoir écrit des données dans votre table, passez à l' Étape 3 : lire des données à partir d'une table.