Sobes.tech
Junior

What is the difference between the execute, executeQuery, and executeUpdate methods?

sobes.tech AI

Answer from AI

  • executeQuery(): Used to execute SQL statements that return a single result set (e.g., SELECT statements). Returns a ResultSet object.
  • executeUpdate(): Used to execute SQL statements that modify the database and return the number of affected rows (e.g., INSERT, UPDATE, DELETE, CREATE TABLE, DROP TABLE). Returns an int.
  • execute(): A more versatile method. Can execute any type of SQL statement. Returns a boolean indicating whether a ResultSet was returned. If true, the result is a ResultSet. If false, the result is the number of affected rows. To get the actual result, use getResultSet() or getUpdateCount().
Method Purpose Return Value Example Usage
executeQuery Executes SELECT ResultSet Retrieving data from a table.
executeUpdate Executes INSERT, UPDATE, DELETE, DDL int (number of affected rows) Adding, modifying, or deleting records; creating or dropping tables.
execute Any SQL statement boolean (true if a ResultSet is returned) When the statement type is unknown in advance or the statement can return both data and count.

Example of using execute():

// Assuming statement is already created
boolean isResultSet = statement.execute("SELECT * FROM users WHERE id = 1 OR INSERT INTO logs (message) VALUES ('User fetched')");

if (isResultSet) {
    // Handling ResultSet
    try (ResultSet rs = statement.getResultSet()) {
        while (rs.next()) {
            // Reading data
        }
    }
} else {
    // Handling the count of affected rows
    int updateCount = statement.getUpdateCount();
    // Processing updateCount
}