O Amazon Redshift não permitirá mais a criação de UDFs do Python a partir do Patch 198. As UDFs do Python existentes continuarão a funcionar normalmente até 30 de junho de 2026. Para ter mais informações, consulte a publicação de blog
Usar ExecuteStatement com um SDK da AWS
Os exemplos de código a seguir mostram como usar o ExecuteStatement.
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:
- Java
-
- SDK para Java 2.x
-
nota
Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository
. Executa uma instrução SQL para criar uma tabela de banco de dados.
/** * Creates an asynchronous task to execute a SQL statement for creating a new table. * * @param clusterId the identifier of the Amazon Redshift cluster * @param databaseName the name of the database to create the table in * @param userName the username to use for the database connection * @return a {@link CompletableFuture} that completes with the result of the SQL statement execution * @throws RuntimeException if there is an error creating the table */ public CompletableFuture<ExecuteStatementResponse> createTableAsync(String clusterId, String databaseName, String userName) { ExecuteStatementRequest createTableRequest = ExecuteStatementRequest.builder() .clusterIdentifier(clusterId) .dbUser(userName) .database(databaseName) .sql("CREATE TABLE Movies (" + "id INT PRIMARY KEY, " + "title VARCHAR(100), " + "year INT)") .build(); return getAsyncDataClient().executeStatement(createTableRequest) .whenComplete((response, exception) -> { if (exception != null) { throw new RuntimeException("Error creating table: " + exception.getMessage(), exception); } else { logger.info("Table created: Movies"); } }); }Executa uma instrução SQL para inserir dados em uma tabela de banco de dados.
/** * Asynchronously pops a table from a JSON file. * * @param clusterId the ID of the cluster * @param databaseName the name of the database * @param userName the username * @param fileName the name of the JSON file * @param number the number of records to process * @return a CompletableFuture that completes with the number of records added to the Movies table */ public CompletableFuture<Integer> popTableAsync(String clusterId, String databaseName, String userName, String fileName, int number) { return CompletableFuture.supplyAsync(() -> { try { JsonParser parser = new JsonFactory().createParser(new File(fileName)); JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); return iter; } catch (IOException e) { throw new RuntimeException("Failed to read or parse JSON file: " + e.getMessage(), e); } }).thenCompose(iter -> processNodesAsync(clusterId, databaseName, userName, iter, number)) .whenComplete((result, exception) -> { if (exception != null) { logger.info("Error {} ", exception.getMessage()); } else { logger.info("{} records were added to the Movies table." , result); } }); } private CompletableFuture<Integer> processNodesAsync(String clusterId, String databaseName, String userName, Iterator<JsonNode> iter, int number) { return CompletableFuture.supplyAsync(() -> { int t = 0; try { while (iter.hasNext()) { if (t == number) break; JsonNode currentNode = iter.next(); int year = currentNode.get("year").asInt(); String title = currentNode.get("title").asText(); // Use SqlParameter to avoid SQL injection. List<SqlParameter> parameterList = new ArrayList<>(); String sqlStatement = "INSERT INTO Movies VALUES( :id , :title, :year);"; SqlParameter idParam = SqlParameter.builder() .name("id") .value(String.valueOf(t)) .build(); SqlParameter titleParam = SqlParameter.builder() .name("title") .value(title) .build(); SqlParameter yearParam = SqlParameter.builder() .name("year") .value(String.valueOf(year)) .build(); parameterList.add(idParam); parameterList.add(titleParam); parameterList.add(yearParam); ExecuteStatementRequest insertStatementRequest = ExecuteStatementRequest.builder() .clusterIdentifier(clusterId) .sql(sqlStatement) .database(databaseName) .dbUser(userName) .parameters(parameterList) .build(); getAsyncDataClient().executeStatement(insertStatementRequest); logger.info("Inserted: " + title + " (" + year + ")"); t++; } } catch (RedshiftDataException e) { throw new RuntimeException("Error inserting data: " + e.getMessage(), e); } return t; }); }Executa uma instrução SQL para consultar uma tabela de banco de dados.
/** * Asynchronously queries movies by a given year from a Redshift database. * * @param database the name of the database to query * @param dbUser the user to connect to the database with * @param year the year to filter the movies by * @param clusterId the identifier of the Redshift cluster to connect to * @return a {@link CompletableFuture} containing the response ID of the executed SQL statement */ public CompletableFuture<String> queryMoviesByYearAsync(String database, String dbUser, int year, String clusterId) { String sqlStatement = "SELECT * FROM Movies WHERE year = :year"; SqlParameter yearParam = SqlParameter.builder() .name("year") .value(String.valueOf(year)) .build(); ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder() .clusterIdentifier(clusterId) .database(database) .dbUser(dbUser) .parameters(yearParam) .sql(sqlStatement) .build(); return CompletableFuture.supplyAsync(() -> { try { ExecuteStatementResponse response = getAsyncDataClient().executeStatement(statementRequest).join(); // Use join() to wait for the result return response.id(); } catch (RedshiftDataException e) { throw new RuntimeException("Error executing statement: " + e.getMessage(), e); } }).exceptionally(exception -> { logger.info("Error: {}", exception.getMessage()); return ""; }); }-
Consulte detalhes da API em ExecuteStatement na Referência da API AWS SDK for Java 2.x.
-
- SAP ABAP
-
- SDK para SAP ABAP
-
nota
Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository
. TRY. " Example values: iv_cluster_identifier = 'redshift-cluster-movies' " Example values: iv_database_name = 'dev' " Example values: iv_user_name = 'awsuser' " Example values: iv_sql = 'SELECT * FROM movies WHERE year = :year' " Example values: it_parameter_list - SQL parameters for parameterized queries " Only pass parameters if the list is not empty IF it_parameter_list IS NOT INITIAL. oo_result = lo_rsd->executestatement( iv_clusteridentifier = iv_cluster_identifier iv_database = iv_database_name iv_dbuser = iv_user_name iv_sql = iv_sql it_parameters = it_parameter_list ). ELSE. oo_result = lo_rsd->executestatement( iv_clusteridentifier = iv_cluster_identifier iv_database = iv_database_name iv_dbuser = iv_user_name iv_sql = iv_sql ). ENDIF. lv_statement_id = oo_result->get_id( ). MESSAGE |Statement executed. ID: { lv_statement_id }| TYPE 'I'. CATCH /aws1/cx_rsdexecutestatementex. MESSAGE 'Statement execution error.' TYPE 'I'. CATCH /aws1/cx_rsdresourcenotfoundex. MESSAGE 'Resource not found.' TYPE 'I'. ENDTRY.-
Para ver detalhes da API, consulte ExecuteStatement na Referência de API do SDK da AWS para SAP ABAP.
-
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.