Utilizzare DeleteTable con un SDK AWS o una CLI
Gli esempi di codice seguenti mostrano come utilizzare DeleteTable.
Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nei seguenti esempi di codice:
- .NET
-
- SDK per .NET (v4)
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. /// <summary> /// Deletes a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteTableAsync(string tableName) { try { var request = new DeleteTableRequest { TableName = tableName, }; var response = await _amazonDynamoDB.DeleteTableAsync(request); Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted."); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}"); return false; } }-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK per .NET.
-
- Bash
-
- AWS CLI con script Bash
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. ############################################################################### # function dynamodb_delete_table # # This function deletes a DynamoDB table. # # Parameters: # -n table_name -- The name of the table to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function dynamodb_delete_table() { local table_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function dynamodb_delete_table" echo "Deletes an Amazon DynamoDB table." echo " -n table_name -- The name of the table to delete." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) table_name="${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 iecho "Parameters:\n" iecho " table_name: $table_name" iecho "" response=$(aws dynamodb delete-table \ --table-name "$table_name") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-table operation failed.$response" return 1 fi return 0 }Le funzioni di utilità utilizzate in questo esempio.
############################################################################### # 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 }-
Per informazioni dettagliate sulla API, consulta DeleteTable nella Documentazione di riferimento di AWS CLI.
-
- C++
-
- SDK per C++
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. //! 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(); }-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK per C++.
-
- CLI
-
- AWS CLI
-
Per eliminare una tabella
Nell’esempio seguente
delete-tableelimina la tabellaMusicCollection.aws dynamodb delete-table \ --table-nameMusicCollectionOutput:
{ "TableDescription": { "TableStatus": "DELETING", "TableSizeBytes": 0, "ItemCount": 0, "TableName": "MusicCollection", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "WriteCapacityUnits": 5, "ReadCapacityUnits": 5 } } }Per ulteriori informazioni, consulta Eliminazione di una tabella nella Guida per gli sviluppatori di Amazon DynamoDB.
-
Per informazioni dettagliate sulla API, consulta DeleteTable
nella Documentazione di riferimento di AWS CLI.
-
- Go
-
- SDK per Go V2
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. import ( "context" "errors" "log" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" "github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" ) // 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 } // DeleteTable deletes the DynamoDB table and all of its data. func (basics TableBasics) DeleteTable(ctx context.Context) error { _, err := basics.DynamoDbClient.DeleteTable(ctx, &dynamodb.DeleteTableInput{ TableName: aws.String(basics.TableName)}) if err != nil { log.Printf("Couldn't delete table %v. Here's why: %v\n", basics.TableName, err) } return err }-
Per informazioni dettagliate sulle API, consulta DeleteTable
nella Documentazione di riferimento delle API AWS SDK per Go.
-
- Java
-
- SDK per Java 2.x
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; /** * 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 */ public class DeleteTable { public static void main(String[] args) { final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table to delete (for example, Music3). **Warning** This program will delete the table that you specify! """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = args[0]; System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); deleteDynamoDBTable(ddb, tableName); ddb.close(); } public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() .tableName(tableName) .build(); try { ddb.deleteTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println(tableName + " was successfully deleted!"); } }-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK for Java 2.x.
-
- JavaScript
-
- SDK per JavaScript (v3)
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. import { DeleteTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new DeleteTableCommand({ TableName: "DecafCoffees", }); const response = await client.send(command); console.log(response); return response; };-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK per JavaScript.
-
- SDK per JavaScript (v2)
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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: process.argv[2], }; // Call DynamoDB to delete the specified table ddb.deleteTable(params, function (err, data) { if (err && err.code === "ResourceNotFoundException") { console.log("Error: Table not found"); } else if (err && err.code === "ResourceInUseException") { console.log("Error: Table in use"); } else { console.log("Success", data); } });-
Per ulteriori informazioni, consulta la Guida per sviluppatori di AWS SDK per JavaScript.
-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK per JavaScript.
-
- Kotlin
-
- SDK per Kotlin
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. suspend fun deleteDynamoDBTable(tableNameVal: String) { val request = DeleteTableRequest { tableName = tableNameVal } DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb -> ddb.deleteTable(request) println("$tableNameVal was deleted") } }-
Per informazioni dettagliate sulle API, consultare DeleteTable
nella Documentazione di riferimento delle API SDK AWS per Kotlin.
-
- PHP
-
- SDK per PHP
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. public function deleteTable(string $TableName) { $this->customWaiter(function () use ($TableName) { return $this->dynamoDbClient->deleteTable([ 'TableName' => $TableName, ]); }); }-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK per PHP.
-
- PowerShell
-
- Strumenti per PowerShell V4
-
Esempio 1: elimina la tabella specificata. Prima di procedere con l’operazione, viene richiesta una conferma.
Remove-DDBTable -TableName "myTable"Esempio 2: elimina la tabella specificata. Prima di procedere con l’operazione, non viene richiesta una conferma.
Remove-DDBTable -TableName "myTable" -Force-
Per informazioni dettagliate sull’API, consulta DeleteTable nella documentazione di riferimento dei cmdlet di AWS Strumenti per PowerShell (V4).
-
- Strumenti per PowerShell V5
-
Esempio 1: elimina la tabella specificata. Prima di procedere con l’operazione, viene richiesta una conferma.
Remove-DDBTable -TableName "myTable"Esempio 2: elimina la tabella specificata. Prima di procedere con l’operazione, non viene richiesta una conferma.
Remove-DDBTable -TableName "myTable" -Force-
Per informazioni dettagliate sull’API, consulta DeleteTable nella documentazione di riferimento dei cmdlet di AWS Strumenti per PowerShell (V5).
-
- Python
-
- SDK per Python (Boto3)
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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 delete_table(self): """ Deletes the table. """ try: self.table.delete() self.table = None except ClientError as err: logger.error( "Couldn't delete table. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API SDK AWS per Python (Boto3).
-
- Ruby
-
- SDK per Ruby
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. # Encapsulates an Amazon DynamoDB table of movie data. class Scaffold attr_reader :dynamo_resource, :table_name, :table def initialize(table_name) client = Aws::DynamoDB::Client.new(region: 'us-east-1') @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table_name = table_name @table = nil @logger = Logger.new($stdout) @logger.level = Logger::DEBUG end # Deletes the table. def delete_table @table.delete @table = nil rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't delete table. Here's why:") puts("\t#{e.code}: #{e.message}") raise end-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento delle API AWS SDK per Ruby.
-
- Rust
-
- SDK per Rust
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. pub async fn delete_table(client: &Client, table: &str) -> Result<DeleteTableOutput, Error> { let resp = client.delete_table().table_name(table).send().await; match resp { Ok(out) => { println!("Deleted table"); Ok(out) } Err(e) => Err(Error::Unhandled(e.into())), } }-
Per informazioni dettagliate sulle API, consulta DeleteTable
nella Documentazione di riferimento delle API SDK AWS per Rust.
-
- SAP ABAP
-
- SDK per SAP ABAP
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. TRY. lo_dyn->deletetable( iv_tablename = iv_table_name ). " Wait till the table is actually deleted. lo_dyn->get_waiter( )->tablenotexists( iv_max_wait_time = 200 iv_tablename = iv_table_name ). MESSAGE 'Table ' && iv_table_name && ' deleted.' TYPE 'I'. CATCH /aws1/cx_dynresourcenotfoundex. MESSAGE 'The table ' && iv_table_name && ' does not exist' TYPE 'E'. CATCH /aws1/cx_dynresourceinuseex. MESSAGE 'The table cannot be deleted since it is in use' TYPE 'E'. ENDTRY.-
Per informazioni dettagliate sulle API, consulta DeleteTable nella Documentazione di riferimento dell'API dell'AWS SDK per SAP ABAP.
-
- Swift
-
- SDK per Swift
-
Nota
Ulteriori informazioni su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. import AWSDynamoDB /// /// Deletes the table from Amazon DynamoDB. /// func deleteTable() async throws { do { guard let client = self.ddbClient else { throw MoviesError.UninitializedClient } let input = DeleteTableInput( tableName: self.tableName ) _ = try await client.deleteTable(input: input) } catch { print("ERROR: deleteTable:", dump(error)) throw error } }-
Per informazioni dettagliate sulle API, consulta DeleteTable
nella Documentazione di riferimento delle API SDK AWS per Swift.
-
Per un elenco completo delle guide per gli sviluppatori di SDK AWS ed esempi di codice, consulta la sezione Utilizzo di DynamoDB con un SDK AWS. Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.