O Amazon Redshift não permitirá mais a criação de funções definidas pelo usuário (UDFs) do Python a partir de 1.º de novembro de 2025. Se quiser usar UDFs do Python, você deve criá-las antes dessa data. As UDFs do Python existentes continuarão a funcionar normalmente. Para ter mais informações, consulte a publicação de blog .
Usar GetStatementResult com um SDK da AWS
Os exemplos de código a seguir mostram como usar o GetStatementResult.
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 em contexto no seguinte exemplo de código:
- .NET
-
- SDK for .NET (v4)
-
/// <summary>
/// Get the results of a statement execution.
/// </summary>
/// <param name="statementId">The statement ID.</param>
/// <returns>A list of result rows.</returns>
public async Task<List<List<Field>>> GetStatementResultAsync(string statementId)
{
try
{
var request = new GetStatementResultRequest
{
Id = statementId
};
var response = await _redshiftDataClient.GetStatementResultAsync(request);
return response.Records;
}
catch (Amazon.RedshiftDataAPIService.Model.ResourceNotFoundException ex)
{
Console.WriteLine($"Statement not found: {ex.Message}");
throw;
}
catch (Exception ex)
{
Console.WriteLine($"Couldn't get statement result. Here's why: {ex.Message}");
throw;
}
}
- Java
-
- SDK para Java 2.x
-
Verifique o resultado da instrução
/**
* Asynchronously retrieves the results of a statement execution.
*
* @param statementId the ID of the statement for which to retrieve the results
* @return a {@link CompletableFuture} that completes when the statement result has been processed
*/
public CompletableFuture<Void> getResultsAsync(String statementId) {
GetStatementResultRequest resultRequest = GetStatementResultRequest.builder()
.id(statementId)
.build();
return getAsyncDataClient().getStatementResult(resultRequest)
.handle((response, exception) -> {
if (exception != null) {
logger.info("Error getting statement result {} ", exception.getMessage());
throw new RuntimeException("Error getting statement result: " + exception.getMessage(), exception);
}
// Extract and print the field values using streams if the response is valid.
response.records().stream()
.flatMap(List::stream)
.map(Field::stringValue)
.filter(value -> value != null)
.forEach(value -> System.out.println("The Movie title field is " + value));
return response;
}).thenAccept(response -> {
// Optionally add more logic here if needed after handling the response
});
}
- Python
-
- SDK para Python (Boto3).
-
class RedshiftDataWrapper:
"""Encapsulates Amazon Redshift data."""
def __init__(self, client):
"""
:param client: A Boto3 RedshiftDataWrapper client.
"""
self.client = client
def get_statement_result(self, statement_id):
"""
Gets the result of a SQL statement.
:param statement_id: The SQL statement identifier.
:return: The SQL statement result.
"""
try:
result = {
"Records": [],
}
paginator = self.client.get_paginator("get_statement_result")
for page in paginator.paginate(Id=statement_id):
if "ColumnMetadata" not in result:
result["ColumnMetadata"] = page["ColumnMetadata"]
result["Records"].extend(page["Records"])
return result
except ClientError as err:
logging.error(
"Couldn't get statement result. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
O código a seguir instancia o objeto RedshiftDataWrapper.
client = boto3.client("redshift-data")
redshift_data_wrapper = RedshiftDataWrapper(client)
Para ver uma lista completa dos guias de desenvolvedor e exemplos de código do SDK da AWS, consulte Usar este serviço com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.