适用于使用 Amazon SDK 的 Amazon RDS 的代码示例
以下代码示例展示如何将 Amazon RDS 与 Amazon 软件开发工具包(SDK)一起使用。
基础知识是向您展示如何在服务中执行基本操作的代码示例。
操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。
场景是向您展示如何通过在一个服务中调用多个函数或与其他 Amazon Web Services 服务 结合来完成特定任务的代码示例。
有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。
开始使用
以下代码示例演示了如何开始使用 Amazon RDS。
- .NET
-
- Amazon SDK for .NET
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 using System; using System.Threading.Tasks; using Amazon.RDS; using Amazon.RDS.Model; namespace RDSActions; public static class HelloRds { static async Task Main(string[] args) { var rdsClient = new AmazonRDSClient(); Console.WriteLine($"Hello Amazon RDS! Following are some of your DB instances:"); Console.WriteLine(); // You can use await and any of the async methods to get a response. // Let's get the first twenty DB instances. var response = await rdsClient.DescribeDBInstancesAsync( new DescribeDBInstancesRequest() { MaxRecords = 20 // Must be between 20 and 100. }); foreach (var instance in response.DBInstances) { Console.WriteLine($"\tDB name: {instance.DBName}"); Console.WriteLine($"\tArn: {instance.DBInstanceArn}"); Console.WriteLine($"\tIdentifier: {instance.DBInstanceIdentifier}"); Console.WriteLine(); } } }
-
有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DescribeDBInstances。
-
- C++
-
- SDK for C++
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 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_rds") # 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_rds.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})
hello_rds.cpp 源文件的代码。
#include <aws/core/Aws.h> #include <aws/rds/RDSClient.h> #include <aws/rds/model/DescribeDBInstancesRequest.h> #include <iostream> /* * A "Hello Rds" starter application which initializes an Amazon Relational Database Service (Amazon RDS) client and * describes the Amazon RDS instances. * * main function * * Usage: 'hello_rds' * */ 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; std::vector<Aws::String> instanceDBIDs; do { Aws::RDS::Model::DescribeDBInstancesRequest request; if (!marker.empty()) { request.SetMarker(marker); } Aws::RDS::Model::DescribeDBInstancesOutcome outcome = rdsClient.DescribeDBInstances(request); if (outcome.IsSuccess()) { for (auto &instance: outcome.GetResult().GetDBInstances()) { instanceDBIDs.push_back(instance.GetDBInstanceIdentifier()); } marker = outcome.GetResult().GetMarker(); } else { result = 1; std::cerr << "Error with RDS::DescribeDBInstances. " << outcome.GetError().GetMessage() << std::endl; break; } } while (!marker.empty()); std::cout << instanceDBIDs.size() << " RDS instances found." << std::endl; for (auto &instanceDBID: instanceDBIDs) { std::cout << " Instance: " << instanceDBID << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
-
有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 DescribeDBInstances。
-
- Go
-
- 适用于 Go V2 的 SDK
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 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 Relational Database Service (Amazon RDS) // client and list up to 20 DB instances 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 } rdsClient := rds.NewFromConfig(sdkConfig) const maxInstances = 20 fmt.Printf("Let's list up to %v DB instances.\n", maxInstances) output, err := rdsClient.DescribeDBInstances(ctx, &rds.DescribeDBInstancesInput{MaxRecords: aws.Int32(maxInstances)}) if err != nil { fmt.Printf("Couldn't list DB instances: %v\n", err) return } if len(output.DBInstances) == 0 { fmt.Println("No DB instances found.") } else { for _, instance := range output.DBInstances { fmt.Printf("DB instance %v has database %v.\n", *instance.DBInstanceIdentifier, *instance.DBName) } } }
-
有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DescribeDBInstances
。
-
- Java
-
- SDK for Java 2.x
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.RdsException; import java.util.List; /** * 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 DescribeDBInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); describeInstances(rdsClient); rdsClient.close(); } public static void describeInstances(RdsClient rdsClient) { try { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { System.out.println("Instance ARN is: " + instance.dbInstanceArn()); System.out.println("The Engine is " + instance.engine()); System.out.println("Connection endpoint is" + instance.endpoint().address()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DescribeDBInstances。
-
- Python
-
- SDK for Python (Boto3)
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 """ Purpose Shows how to use the AWS SDK for Python (Boto3) with the Amazon Relational Database Service (Amazon RDS) to list the databases in your account. """ import boto3 from botocore.exceptions import ClientError # Create an RDS client rds_client = boto3.client("rds") # Create a paginator for the describe_db_instances operation paginator = rds_client.get_paginator("describe_db_instances") try: # Use the paginator to get a list of DB instances response_iterator = paginator.paginate( PaginationConfig={ "MaxItems": 123, "PageSize": 50, # Adjust PageSize as needed "StartingToken": None, } ) # Iterate through the pages of the response instances_found = False for page in response_iterator: if "DBInstances" in page and page["DBInstances"]: instances_found = True print("Your RDS instances are:") for db in page["DBInstances"]: print(db["DBInstanceIdentifier"]) if not instances_found: print("No RDS instances found!") except ClientError as e: print(f"Couldn't list RDS instances. Here's why: {e.response['Error']['Message']}")
-
有关 API 详细信息,请参阅《适用于 Python 的 Amazon SDK(Boto3)API 参考》中的 DescribeDBInstances。
-
- Ruby
-
- 适用于 Ruby 的 SDK
-
注意
查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 require 'aws-sdk-rds' require 'logger' # RDSManager is a class responsible for managing RDS operations # such as listing all RDS DB instances in the current AWS account. class RDSManager def initialize(client) @client = client @logger = Logger.new($stdout) end # Lists and prints all RDS DB instances in the current AWS account. def list_db_instances @logger.info('Listing RDS DB instances') paginator = @client.describe_db_instances instances = [] paginator.each_page do |page| instances.concat(page.db_instances) end if instances.empty? @logger.info('No instances found.') else @logger.info("Found #{instances.count} instance(s):") instances.each do |instance| @logger.info(" * #{instance.db_instance_identifier} (#{instance.db_instance_status})") end end end end if $PROGRAM_NAME == __FILE__ rds_client = Aws::RDS::Client.new(region: 'us-west-2') manager = RDSManager.new(rds_client) manager.list_db_instances end
-
有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 DescribeDBInstances。
-
代码示例
- 基础知识
- Hello Amazon RDS
- 了解基础知识
- 操作
- CreateDBInstance
- CreateDBParameterGroup
- CreateDBSnapshot
- DeleteDBInstance
- DeleteDBParameterGroup
- DescribeAccountAttributes
- DescribeDBEngineVersions
- DescribeDBInstances
- DescribeDBParameterGroups
- DescribeDBParameters
- DescribeDBSnapshots
- DescribeOrderableDBInstanceOptions
- GenerateRDSAuthToken
- ModifyDBInstance
- ModifyDBParameterGroup
- RebootDBInstance
- 场景
- 无服务器示例