View a markdown version of this page

Usa CreateDBSnapshot con un AWS SDK o CLI - AWS Esempi di codice SDK

Sono disponibili altri esempi AWS SDK nel repository AWS Doc SDK Examples. GitHub

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Usa CreateDBSnapshot con un AWS SDK o CLI

Gli esempi di codice seguenti mostrano come utilizzare CreateDBSnapshot.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

.NET
SDK per .NET
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Create a snapshot of a DB instance. /// </summary> /// <param name="dbInstanceIdentifier">DB instance identifier.</param> /// <param name="snapshotIdentifier">Identifier for the snapshot.</param> /// <returns>DB snapshot object.</returns> public async Task<DBSnapshot> CreateDBSnapshot(string dbInstanceIdentifier, string snapshotIdentifier) { var response = await _amazonRDS.CreateDBSnapshotAsync( new CreateDBSnapshotRequest() { DBSnapshotIdentifier = snapshotIdentifier, DBInstanceIdentifier = dbInstanceIdentifier }); return response.DBSnapshot; }
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK per .NET .

C++
SDK per C++
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient client(clientConfig); Aws::RDS::Model::CreateDBSnapshotRequest request; request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER); request.SetDBSnapshotIdentifier(snapshotID); Aws::RDS::Model::CreateDBSnapshotOutcome outcome = client.CreateDBSnapshot(request); if (outcome.IsSuccess()) { std::cout << "Snapshot creation has started." << std::endl; } else { std::cerr << "Error with RDS::CreateDBSnapshot. " << outcome.GetError().GetMessage() << std::endl; cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client); return false; }
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK per C++ .

CLI
AWS CLI

Come creare uno snapshot del database

L’esempio create-db-snapshot seguente crea uno snapshot del database.

aws rds create-db-snapshot \ --db-instance-identifier database-mysql \ --db-snapshot-identifier mydbsnapshot

Output:

{ "DBSnapshot": { "DBSnapshotIdentifier": "mydbsnapshot", "DBInstanceIdentifier": "database-mysql", "Engine": "mysql", "AllocatedStorage": 100, "Status": "creating", "Port": 3306, "AvailabilityZone": "us-east-1b", "VpcId": "vpc-6594f31c", "InstanceCreateTime": "2019-04-30T15:45:53.663Z", "MasterUsername": "admin", "EngineVersion": "5.6.40", "LicenseModel": "general-public-license", "SnapshotType": "manual", "Iops": 1000, "OptionGroupName": "default:mysql-5-6", "PercentProgress": 0, "StorageType": "io1", "Encrypted": true, "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE", "DBSnapshotArn": "arn:aws:rds:us-east-1:123456789012:snapshot:mydbsnapshot", "IAMDatabaseAuthenticationEnabled": false, "ProcessorFeatures": [], "DbiResourceId": "db-AKIAIOSFODNN7EXAMPLE" } }

Per ulteriori informazioni, consulta Creazione di uno snapshot di database nella Guida per l’utente di Amazon RDS.

  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot in AWS CLI Command Reference.

Go
SDK per Go V2
Nota

C'è dell'altro 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" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/rds" "github.com/aws/aws-sdk-go-v2/service/rds/types" ) type DbInstances struct { RdsClient *rds.Client } // CreateSnapshot creates a snapshot of a DB instance. func (instances *DbInstances) CreateSnapshot(ctx context.Context, instanceName string, snapshotName string) ( *types.DBSnapshot, error) { output, err := instances.RdsClient.CreateDBSnapshot(ctx, &rds.CreateDBSnapshotInput{ DBInstanceIdentifier: aws.String(instanceName), DBSnapshotIdentifier: aws.String(snapshotName), }) if err != nil { log.Printf("Couldn't create snapshot %v: %v\n", snapshotName, err) return nil, err } else { return output.DBSnapshot, nil } }
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK per Go .

Java
SDK per Java 2.x
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

// Create an Amazon RDS snapshot. public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { try { CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .dbSnapshotIdentifier(dbSnapshotIdentifier) .build(); CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest); System.out.println("The Snapshot id is " + response.dbSnapshot().dbiResourceId()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK for Java 2.x .

PHP
SDK per PHP
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

require __DIR__ . '/vendor/autoload.php'; use Aws\Exception\AwsException; $rdsClient = new Aws\Rds\RdsClient([ 'region' => 'us-east-2' ]); $dbIdentifier = '<<{{db-identifier}}>>'; $snapshotName = '<<{{backup_2018_12_25}}>>'; try { $result = $rdsClient->createDBSnapshot([ 'DBInstanceIdentifier' => $dbIdentifier, 'DBSnapshotIdentifier' => $snapshotName, ]); var_dump($result); } catch (AwsException $e) { echo $e->getMessage(); echo "\n"; }
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK per PHP .

Python
SDK per Python (Boto3)
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

class InstanceWrapper: """Encapsulates Amazon RDS DB instance actions.""" def __init__(self, rds_client): """ :param rds_client: A Boto3 Amazon RDS client. """ self.rds_client = rds_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ rds_client = boto3.client("rds") return cls(rds_client) def create_snapshot(self, snapshot_id, instance_id): """ Creates a snapshot of a DB instance. :param snapshot_id: The ID to give the created snapshot. :param instance_id: The ID of the DB instance to snapshot. :return: Data about the newly created snapshot. """ try: response = self.rds_client.create_db_snapshot( DBSnapshotIdentifier=snapshot_id, DBInstanceIdentifier=instance_id ) snapshot = response["DBSnapshot"] except ClientError as err: logger.error( "Couldn't create snapshot of %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return snapshot
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API SDK AWS per Python (Boto3).

Ruby
SDK per Ruby
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

require 'aws-sdk-rds' # v2: require 'aws-sdk' # Create a snapshot for an Amazon Relational Database Service (Amazon RDS) # DB instance. # # @param rds_resource [Aws::RDS::Resource] The resource containing SDK logic. # @param db_instance_name [String] The name of the Amazon RDS DB instance. # @return [Aws::RDS::DBSnapshot, nil] The snapshot created, or nil if error. def create_snapshot(rds_resource, db_instance_name) id = "snapshot-#{rand(10**6)}" db_instance = rds_resource.db_instance(db_instance_name) db_instance.create_snapshot({ db_snapshot_identifier: id }) rescue Aws::Errors::ServiceError => e puts "Couldn't create DB instance snapshot #{id}:\n #{e.message}" end
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK per Ruby .

Swift
SDK per Swift
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

import AWSRDS /// Create a snapshot of the specified name. /// /// - Parameters: /// - instanceIdentifier: The identifier of the database instance to /// snapshot. /// - snapshotIdentifier: A unique identifier to give the newly-created /// snapshot. func createDBSnapshot(instanceIdentifier: String, snapshotIdentifier: String) async { do { let output = try await rdsClient.createDBSnapshot( input: CreateDBSnapshotInput( dbInstanceIdentifier: instanceIdentifier, dbSnapshotIdentifier: snapshotIdentifier ) ) guard let snapshot = output.dbSnapshot else { print("No snapshot returned.") return } print("The snapshot has been created with ID \(snapshot.dbiResourceId ?? "<unknown>")") } catch { print("*** Unable to create the database snapshot named \(snapshotIdentifier): \(error.localizedDescription)") } }
  • Per informazioni dettagliate sull’API, consulta CreateDBSnapshot nella documentazione di riferimento dell’API AWS SDK per Swift.