JDBC, query returns false but saved in database

Asked

Viewed 240 times

0

I am running the following java function:

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 select users, it appears that they have been registered.

2 answers

2


Ricardo,

Will surely return false, for the execute() is not specific for entering data although it works as well. You should have used the executeUpdate(), in this case, command of INSERT is regarded as update.

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

If we look at the Java documentation on 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 have marked in bold above. In case you are performing INSERT through the execute(), the result will be false because the INSERT is understood as an operation of "update".

  • I understood, but the executionUpdate() returns an int...

  • This, this int indicates the number of inserted records, which in this case should be 1 for successful insertion cases. If the insertion has failed, it will return something other than that, which is 0. Anything take a look here: http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#executeUpdate()

  • I did it, Obg !

0

This is because the method execute 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.

By persisting in your code the return will be a contador de update informing the amount of entered records.

Source: Oracle Java SE 7 Documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.