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.,SELECTstatements). Returns aResultSetobject.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 anint.execute(): A more versatile method. Can execute any type of SQL statement. Returns abooleanindicating whether aResultSetwas returned. Iftrue, the result is aResultSet. Iffalse, the result is the number of affected rows. To get the actual result, usegetResultSet()orgetUpdateCount().
| 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
}