Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples
As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Use DescribeDBEngineVersions
com um AWS SDK
Os exemplos de código a seguir mostram como usar o DescribeDBEngineVersions
.
Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:
- .NET
-
- AWS SDK for .NET
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. /// <summary> /// Get a list of DB engine versions for a particular DB engine. /// </summary> /// <param name="engine">The name of the engine.</param> /// <param name="parameterGroupFamily">Optional parameter group family name.</param> /// <returns>A list of DBEngineVersions.</returns> public async Task<List<DBEngineVersion>> DescribeDBEngineVersionsForEngineAsync(string engine, string? parameterGroupFamily = null) { var response = await _amazonRDS.DescribeDBEngineVersionsAsync( new DescribeDBEngineVersionsRequest() { Engine = engine, DBParameterGroupFamily = parameterGroupFamily }); return response.DBEngineVersions; }
-
Para API obter detalhes, consulte D escribeDBEngine Versions in AWS SDK for .NET APIReference.
-
- C++
-
- SDKpara C++
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient client(clientConfig); //! Routine which gets available DB engine versions for an engine name and //! an optional parameter group family. /*! \sa getDBEngineVersions() \param engineName: A DB engine name. \param parameterGroupFamily: A parameter group family name, ignored if empty. \param engineVersionsResult: Vector of 'DBEngineVersion' objects returned by the routine. \param client: 'RDSClient' instance. \return bool: Successful completion. */ bool AwsDoc::Aurora::getDBEngineVersions(const Aws::String &engineName, const Aws::String ¶meterGroupFamily, Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersionsResult, const Aws::RDS::RDSClient &client) { Aws::RDS::Model::DescribeDBEngineVersionsRequest request; request.SetEngine(engineName); if (!parameterGroupFamily.empty()) { request.SetDBParameterGroupFamily(parameterGroupFamily); } engineVersionsResult.clear(); Aws::String marker; // The marker is used for pagination. do { if (!marker.empty()) { request.SetMarker(marker); } Aws::RDS::Model::DescribeDBEngineVersionsOutcome outcome = client.DescribeDBEngineVersions(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersions = outcome.GetResult().GetDBEngineVersions(); engineVersionsResult.insert(engineVersionsResult.end(), engineVersions.begin(), engineVersions.end()); marker = outcome.GetResult().GetMarker(); } else { std::cerr << "Error with Aurora::DescribeDBEngineVersionsRequest. " << outcome.GetError().GetMessage() << std::endl; } } while (!marker.empty()); return true; }
-
Para API obter detalhes, consulte D escribeDBEngine Versions in AWS SDK for C++ APIReference.
-
- Go
-
- SDKpara Go V2
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 DbClusters struct { AuroraClient *rds.Client } // GetEngineVersions gets database engine versions that are available for the specified engine // and parameter group family. func (clusters *DbClusters) GetEngineVersions(ctx context.Context, engine string, parameterGroupFamily string) ( []types.DBEngineVersion, error) { output, err := clusters.AuroraClient.DescribeDBEngineVersions(ctx, &rds.DescribeDBEngineVersionsInput{ Engine: aws.String(engine), DBParameterGroupFamily: aws.String(parameterGroupFamily), }) if err != nil { log.Printf("Couldn't get engine versions for %v: %v\n", engine, err) return nil, err } else { return output.DBEngineVersions, nil } }
-
Para API obter detalhes, consulte D escribeDBEngine Versions
in AWS SDK for Go APIReference.
-
- Java
-
- SDKpara Java 2.x
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. public static void describeDBEngines(RdsClient rdsClient) { try { DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder() .engine("aurora-mysql") .defaultOnly(true) .maxRecords(20) .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest); List<DBEngineVersion> engines = response.dbEngineVersions(); // Get all DBEngineVersion objects. for (DBEngineVersion engineOb : engines) { System.out.println("The name of the DB parameter group family for the database engine is " + engineOb.dbParameterGroupFamily()); System.out.println("The name of the database engine " + engineOb.engine()); System.out.println("The version number of the database engine " + engineOb.engineVersion()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
Para API obter detalhes, consulte D escribeDBEngine Versions in AWS SDK for Java 2.x APIReference.
-
- Kotlin
-
- SDKpara Kotlin
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. // Get a list of allowed engine versions. suspend fun getAllowedClusterEngines(dbParameterGroupFamilyVal: String?) { val versionsRequest = DescribeDbEngineVersionsRequest { dbParameterGroupFamily = dbParameterGroupFamilyVal engine = "aurora-mysql" } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbEngineVersions(versionsRequest) response.dbEngineVersions?.forEach { dbEngine -> println("The engine version is ${dbEngine.engineVersion}") println("The engine description is ${dbEngine.dbEngineDescription}") } } }
-
Para API obter detalhes, consulte escribeDBEngineVersões D
em AWS SDKpara referência ao Kotlin API.
-
- Python
-
- SDKpara Python (Boto3)
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. class AuroraWrapper: """Encapsulates Aurora DB cluster actions.""" def __init__(self, rds_client): """ :param rds_client: A Boto3 Amazon Relational Database Service (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 get_engine_versions(self, engine, parameter_group_family=None): """ Gets database engine versions that are available for the specified engine and parameter group family. :param engine: The database engine to look up. :param parameter_group_family: When specified, restricts the returned list of engine versions to those that are compatible with this parameter group family. :return: The list of database engine versions. """ try: kwargs = {"Engine": engine} if parameter_group_family is not None: kwargs["DBParameterGroupFamily"] = parameter_group_family response = self.rds_client.describe_db_engine_versions(**kwargs) versions = response["DBEngineVersions"] except ClientError as err: logger.error( "Couldn't get engine versions for %s. Here's why: %s: %s", engine, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return versions
-
Para API obter detalhes, consulte D escribeDBEngine Versions in AWS SDKfor Python (Boto3) Reference. API
-
- Rust
-
- SDKpara Rust
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS
. // Get available engine families for Aurora MySql. rds.DescribeDbEngineVersions(Engine='aurora-mysql') and build a set of the 'DBParameterGroupFamily' field values. I get {aurora-mysql8.0, aurora-mysql5.7}. pub async fn get_engines(&self) -> Result<HashMap<String, Vec<String>>, ScenarioError> { let describe_db_engine_versions = self.rds.describe_db_engine_versions(DB_ENGINE).await; trace!(versions=?describe_db_engine_versions, "full list of versions"); if let Err(err) = describe_db_engine_versions { return Err(ScenarioError::new( "Failed to retrieve DB Engine Versions", &err, )); }; let version_count = describe_db_engine_versions .as_ref() .map(|o| o.db_engine_versions().len()) .unwrap_or_default(); info!(version_count, "got list of versions"); // Create a map of engine families to their available versions. let mut versions = HashMap::<String, Vec<String>>::new(); describe_db_engine_versions .unwrap() .db_engine_versions() .iter() .filter_map( |v| match (&v.db_parameter_group_family, &v.engine_version) { (Some(family), Some(version)) => Some((family.clone(), version.clone())), _ => None, }, ) .for_each(|(family, version)| versions.entry(family).or_default().push(version)); Ok(versions) } pub async fn describe_db_engine_versions( &self, engine: &str, ) -> Result<DescribeDbEngineVersionsOutput, SdkError<DescribeDBEngineVersionsError>> { self.inner .describe_db_engine_versions() .engine(engine) .send() .await } #[tokio::test] async fn test_scenario_get_engines() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_describe_db_engine_versions() .with(eq("aurora-mysql")) .return_once(|_| { Ok(DescribeDbEngineVersionsOutput::builder() .db_engine_versions( DbEngineVersion::builder() .db_parameter_group_family("f1") .engine_version("f1a") .build(), ) .db_engine_versions( DbEngineVersion::builder() .db_parameter_group_family("f1") .engine_version("f1b") .build(), ) .db_engine_versions( DbEngineVersion::builder() .db_parameter_group_family("f2") .engine_version("f2a") .build(), ) .db_engine_versions(DbEngineVersion::builder().build()) .build()) }); let scenario = AuroraScenario::new(mock_rds); let versions_map = scenario.get_engines().await; assert_eq!( versions_map, Ok(HashMap::from([ ("f1".into(), vec!["f1a".into(), "f1b".into()]), ("f2".into(), vec!["f2a".into()]) ])) ); } #[tokio::test] async fn test_scenario_get_engines_failed() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_describe_db_engine_versions() .with(eq("aurora-mysql")) .return_once(|_| { Err(SdkError::service_error( DescribeDBEngineVersionsError::unhandled(Box::new(Error::new( ErrorKind::Other, "describe_db_engine_versions error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); let scenario = AuroraScenario::new(mock_rds); let versions_map = scenario.get_engines().await; assert_matches!( versions_map, Err(ScenarioError { message, context: _ }) if message == "Failed to retrieve DB Engine Versions" ); }
-
Para API obter detalhes, consulte escribeDBEngineVersões D
em AWS SDKpara API referência do Rust.
-