Validate whether the INSERT was executed successfully or not (JTDS)

2

I would like to know a form of validation to know if the insert was executed successfully, I have no idea how to do this because the execute () method does not return anything!

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

I just wanted to know how to validate because if there was an error inserting I would like to give the option to try again !!!

    
asked by anonymous 28.08.2017 / 21:58

3 answers

3

The correct way to use INSERT , UPDATE , and DELETE would be the executeUpdate() ", in which it returns a value of integer type. The method execute() works for CREATE TABLE or ALTER TABLE and returns false or true . Here's how your code should look:

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.
}
    
28.08.2017 / 22:10
1

You can change the execute() by executeUpdate() and test the return value. According to the official documentation:

  

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 to   ResultSet object

     

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

link

    
28.08.2017 / 22:15
1

Do the following:

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
}

According to the executeUpdate() documentation will return 1 case to is successful and 0 is not possible. Also remember that you should treat the SQLException and SQLTimeoutException exceptions that will be thrown by the method.

Using only execute() is not feasible in this case, as it is necessary to verify your return.

    
28.08.2017 / 22:23