2

Gostaria de saber uma forma de validação pra saber se o insert foi executado com sucesso, não tenho a mínima noção de como fazer isso porque o método execute() não retorna nada!!!

Connection connInsert = DriverManager.getConnection(ConnectionURL);
PreparedStatement inserir = connInsert.prepareStatement("INSERT INTO PRODUTO (ID, NOME, QTDE) VALUES (varId, varNome, varQtde)");
inserir.execute();

Apenas queria saber validar porque se deu erro ao inserir gostaria de dar a opção de tentar novamente!!!

3 Respostas 3

3

O correto para usar o INSERT, UPDATE e DELETE seria o método executeUpdate(), no qual retorna um valor do tipo inteiro. O método execute() funciona para CREATE TABLE ou ALTER TABLE e retorna false ou true. Veja abaixo como de fato deve ficar seu código:

PreparedStatement inserir = connInsert.prepareStatement("INSERT INTO PRODUTO (ID, NOME, QTDE) VALUES (varId, varNome, varQtde)");
int result = inserir.executeUpdate();

if(result > 0){
   // produto inserido com sucess
} else {
   // erro ao inserir produto.
}
3
  • eu preciso executar o "inserir.execute()" antes do laço if? 28/08/2017 às 20:18
  • @MarcioVieira desculpe, acabei me atrapalhando. Veja agora se esclarece pra você.
    – viana
    28/08/2017 às 20:24
  • 1
    Boa, resolvido o problema.... Obrigado =D 28/08/2017 às 20:32
1

Você pode trocar o execute() por executeUpdate() e testar o valor de retorno. Conforme a documentação oficial:

int executeUpdate() throws SQLException

Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.

Returns:

either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

Throws:

SQLException - if a database access error occurs; this method is called on a closed PreparedStatement or the SQL statement returns a ResultSet object

SQLTimeoutException - when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement

https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeUpdate()

1

Faça o seguinte:

Connection connInsert = DriverManager.getConnection(ConnectionURL);
PreparedStatement inserir = connInsert.prepareStatement("INSERT INTO PRODUTO (ID, NOME, QTDE) VALUES (varId, varNome, varQtde)");

if(inserir.executeUpdate() > 0) {
    // inserido com sucesso
} else {
    // erro ao inserir
}

De acordo com a documentação do executeUpdate() retornará 1 caso a inserção for bem sucedida e 0 caso não seja possível. Lembrando ainda que você deve tratar as exceções SQLException e SQLTimeoutException que irão ser lançadas pelo método.

Utilizar somente execute() não é viável neste caso, pois é necessário verificar seu retorno.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .