leah
leah

Reputation: 61

Statement.execute() returning false even though changes are made

For this piece of my code here:

sql = "DELETE FROM assignments WHERE assign_mark = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, d1);

boolean rows = statement.execute();
if (rows == true) {
    new ViewDatabase(user, name, pswrd);
    System.out.println("ASSIGN - ASSIGN_MARK UPDATE SUCCESSFUL!");
    frame.setVisible(false);
} else if (rows == false) {
    JOptionPane.showMessageDialog(null, "Cannot find row!",
              "ERROR", JOptionPane.ERROR_MESSAGE);
}

statement.close();
connection.close();

After I enter the value of d1 (which corresponds to the correct column of an existing data in my database), I get the "Cannot find row!" value. However, when I check my database, said row with d1 in column name is gone. I'm not sure what error/misunderstanding of concept I have here.

Upvotes: 1

Views: 2370

Answers (2)

rzwitserloot
rzwitserloot

Reputation: 103018

The execute() call returns true if the result would otherwise have returned a ResultSet object; it returns false otherwise, i.e. if it wanted to return nothing, or an update count.

For just about all intents and purposes, this means that execute() returns true for SELECT statements and false for everything else, including DELETE, INSERT, and UPDATE statements.

Most of all, it means: Don't ever call that method, it's utterly useless.

executeUpdate or executeQuery is what you want.

--

EDIT: As Mark pointed out in a very useful comment, this answer undeservedly denigrates execute(). Let's just say that the returned boolean is a bit bizarre, but then that's not the only bit of the JDBC API that's a bit unintuitive. The method has its uses; it's just not the right method for this specific question. Do read the comment for more details :)

Upvotes: 5

g00se
g00se

Reputation: 4296

int numColsAffected = statement.executeUpdate();
if (numColsAffected > 0) {
   // Success
}
else {
   // Failure
}

is probably the way to go

Upvotes: 1

Related Questions