JDBC, query returns false but saves in bank

0

I'm running the following function in java:

public boolean insert(User user) throws SQLException{
        String sql = "insert into usuarios (nome, email, senha) values (?,?,?)";
        PreparedStatement instruction = this.connection.prepareStatement(sql);
        instruction.setString(1, user.getName());
        instruction.setString(2, user.getEmail());
        instruction.setString(3, user.getPassword());

        boolean result = instruction.execute();
        instruction.close();
        return result;
    }

The problem is that it always returns false in instruction.execute() but if I make a select in users, it appears that it has been registered.

    
asked by anonymous 11.05.2017 / 15:53

2 answers

2

Ricardo,

It will certainly return false , because execute() is not specific to inserting data even though it works as well. You should have used executeUpdate() , because, in this case, the INSERT command is considered update .

  • executeUpdate() = DML (INSERT, UPDATE and DELETE) commands.
  • executeQuery() = data recovery (SELECT).
  • execute() = DDL commands (CREATE TABLE, ALTER TABLE ...).

If we look at the Java documentation regarding PreparedStatement # execute :

  

Returns: true if the first result is a ResultSet object; false if the   first result is an update count or there is no result.

Notice what I marked in bold above. In case you are performing INSERT through execute() , the result will be false because INSERT is understood as a " .

    
11.05.2017 / 16:17
0

This occurs because the execute method of class PreparedStatement returns true if the first result is an object of type ResultSet and false if the first result is a contador de update or no result

While persisting in your code, the return will be contador de update reporting the number of records entered.

Source: Oracle Java SE 7 Documentation

    
11.05.2017 / 16:18