使用 的 Aurora 程式碼範例 AWS SDKs - Amazon Aurora

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 的 Aurora 程式碼範例 AWS SDKs

下列程式碼範例示範如何搭配 AWS 軟體開發套件 () 使用 AuroraSDK。

基本知識是程式碼範例,示範如何在服務中執行基本操作。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。

案例是程式碼範例,示範如何透過呼叫服務內的多個函數或與其他 結合,來完成特定任務 AWS 服務。

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 使用此服務搭配 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。

開始使用

下列程式碼範例示範如何開始使用 Aurora。

.NET
AWS SDK for .NET
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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}."); } } }
  • 如需API詳細資訊,請參閱AWS SDK for .NET API參考 中的 DescribeDBClusters

C++
SDK 適用於 C++
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

CMakeLists.txt CMake 檔案的程式碼。

# 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 AND AWSSDK_INSTALL_AS_SHARED_LIBS) # 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})

hello_aurora.cpp 來源檔案的程式碼。

#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
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) 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( ctx, &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 適用於 Java 2.x
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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())); } }
  • 如需API詳細資訊,請參閱AWS SDK for Java 2.x API參考 中的 DescribeDBClusters

Python
SDK for Python (Boto3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import boto3 # Create an RDS client rds = boto3.client("rds") # Create a paginator for the describe_db_clusters operation paginator = rds.get_paginator("describe_db_clusters") # Use the paginator to get a list of DB clusters response_iterator = paginator.paginate( PaginationConfig={ "PageSize": 50, # Adjust PageSize as needed "StartingToken": None, } ) # Iterate through the pages of the response clusters_found = False for page in response_iterator: if "DBClusters" in page and page["DBClusters"]: clusters_found = True print("Here are your RDS Aurora clusters:") for cluster in page["DBClusters"]: print( f"Cluster ID: {cluster['DBClusterIdentifier']}, Engine: {cluster['Engine']}" ) if not clusters_found: print("No clusters found!")
  • 如需API詳細資訊,請參閱 中的 DescribeDBClusters AWS SDK for Python (Boto3) API參考

Ruby
SDK 適用於 Ruby
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

require 'aws-sdk-rds' # Creates an Amazon RDS client for the AWS Region rds = Aws::RDS::Client.new puts 'Listing clusters in this AWS account...' # Calls the describe_db_clusters method to get information about clusters resp = rds.describe_db_clusters(max_records: 20) # Checks if any clusters are found and prints the appropriate message if resp.db_clusters.empty? puts 'No clusters found!' else # Loops through the array of cluster objects and prints the cluster identifier resp.db_clusters.each do |cluster| puts "Cluster identifier: #{cluster.db_cluster_identifier}" end end
  • 如需API詳細資訊,請參閱AWS SDK for Ruby API參考 中的 DescribeDBClusters

Rust
SDK for Rust
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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(()) }
  • 如需API詳細資訊,請參閱 中的 DescribeDBClusters AWS SDK for Rust API參考