Code examples for Aurora using Amazon SDKs - Amazon Aurora
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Code examples for Aurora using Amazon SDKs

The following code examples show how to use Aurora with an Amazon software development kit (SDK).

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Cross-service examples are sample applications that work across multiple Amazon Web Services.

For a complete list of Amazon SDK developer guides and code examples, see Using this service with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.

Get started

The following code examples show how to get started using Aurora.

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

using Amazon.RDS; using Amazon.RDS.Model; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace AuroraActions; public static class HelloAurora { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the // Amazon Relational Database Service (Amazon RDS). // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonRDS>() ).Build(); // Now the client is available for injection. Fetching it directly here for example purposes only. var rdsClient = host.Services.GetRequiredService<IAmazonRDS>(); // You can use await and any of the async methods to get a response. var response = await rdsClient.DescribeDBClustersAsync(new DescribeDBClustersRequest { IncludeShared = true }); Console.WriteLine($"Hello Amazon RDS Aurora! Let's list some clusters in this account:"); foreach (var cluster in response.DBClusters) { Console.WriteLine($"\tCluster: database: {cluster.DatabaseName} identifier: {cluster.DBClusterIdentifier}."); } } }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Code for the CMakeLists.txt CMake file.

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS rds) # Set this project's name. project("hello_aurora") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_aurora.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

Code for the hello_aurora.cpp source file.

#include <aws/core/Aws.h> #include <aws/rds/RDSClient.h> #include <aws/rds/model/DescribeDBClustersRequest.h> #include <iostream> /* * A "Hello Aurora" starter application which initializes an Amazon Relational Database Service (Amazon RDS) client * and describes the Amazon Aurora (Aurora) clusters. * * main function * * Usage: 'hello_aurora' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient rdsClient(clientConfig); Aws::String marker; // Used for pagination. std::vector<Aws::String> clusterIds; do { Aws::RDS::Model::DescribeDBClustersRequest request; Aws::RDS::Model::DescribeDBClustersOutcome outcome = rdsClient.DescribeDBClusters(request); if (outcome.IsSuccess()) { for (auto &cluster: outcome.GetResult().GetDBClusters()) { clusterIds.push_back(cluster.GetDBClusterIdentifier()); } marker = outcome.GetResult().GetMarker(); } else { result = 1; std::cerr << "Error with Aurora::GDescribeDBClusters. " << outcome.GetError().GetMessage() << std::endl; break; } } while (!marker.empty()); std::cout << clusterIds.size() << " Aurora clusters found." << std::endl; for (auto &clusterId: clusterIds) { std::cout << " clusterId " << clusterId << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return 0; }
Go
SDK for Go V2
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/rds" ) // main uses the AWS SDK for Go V2 to create an Amazon Aurora client and list up to 20 // DB clusters in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } auroraClient := rds.NewFromConfig(sdkConfig) const maxClusters = 20 fmt.Printf("Let's list up to %v DB clusters.\n", maxClusters) output, err := auroraClient.DescribeDBClusters(context.TODO(), &rds.DescribeDBClustersInput{MaxRecords: aws.Int32(maxClusters)}) if err != nil { fmt.Printf("Couldn't list DB clusters: %v\n", err) return } if len(output.DBClusters) == 0 { fmt.Println("No DB clusters found.") } else { for _, cluster := range output.DBClusters { fmt.Printf("DB cluster %v has database %v.\n", *cluster.DBClusterIdentifier, *cluster.DatabaseName) } } }
Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.paginators.DescribeDBClustersIterable; public class DescribeDbClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); describeClusters(rdsClient); rdsClient.close(); } public static void describeClusters(RdsClient rdsClient) { DescribeDBClustersIterable clustersIterable = rdsClient.describeDBClustersPaginator(); clustersIterable.stream() .flatMap(r -> r.dbClusters().stream()) .forEach(cluster -> System.out .println("Database name: " + cluster.databaseName() + " Arn = " + cluster.dbClusterArn())); } }
Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_sdk_rds::Client; #[derive(Debug)] struct Error(String); impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl std::error::Error for Error {} #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let sdk_config = aws_config::from_env().load().await; let client = Client::new(&sdk_config); let describe_db_clusters_output = client .describe_db_clusters() .send() .await .map_err(|e| Error(e.to_string()))?; println!( "Found {} clusters:", describe_db_clusters_output.db_clusters().len() ); for cluster in describe_db_clusters_output.db_clusters() { let name = cluster.database_name().unwrap_or("Unknown"); let engine = cluster.engine().unwrap_or("Unknown"); let id = cluster.db_cluster_identifier().unwrap_or("Unknown"); let class = cluster.db_cluster_instance_class().unwrap_or("Unknown"); println!("\tDatabase: {name}",); println!("\t Engine: {engine}",); println!("\t ID: {id}",); println!("\tInstance: {class}",); } Ok(()) }