Junior
What is the difference between the methods execute, executeQuery, and executeUpdate?
sobes.tech AI
Answer from AI
executeQuery is used to execute SQL queries that return a single ResultSet object (e.g., SELECT).
executeUpdate is used for executing SQL statements that modify data (e.g., INSERT, UPDATE, DELETE, CREATE TABLE, DROP TABLE). It returns an integer representing the number of affected rows.
execute is used to execute any type of SQL statement. It returns true if the result is a ResultSet (for SELECT queries), and false otherwise. In case of false, to get the number of affected rows or the result of a DDL operation, you need to call getUpdateCount().
// Example of using executeQuery
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
// Process results
}
// Example of using executeUpdate
Statement stmt2 = conn.createStatement();
int updatedRows = stmt2.executeUpdate("UPDATE products SET price = price * 1.1 WHERE category = 'Electronics'");
System.out.println("Updated rows: " + updatedRows);
// Example of using execute
Statement stmt3 = conn.createStatement();
boolean isResultSet = stmt3.execute("SELECT COUNT(*) FROM orders");
if (isResultSet) {
ResultSet rs2 = stmt3.getResultSet();
// Process ResultSet
} else {
int updateCount = stmt3.getUpdateCount();
System.out.println("Updated rows or DDL result: " + updateCount);
}
| Method | Purpose | Return Type | Types of SQL queries |
|---|---|---|---|
execute |
Executes any type of SQL query | boolean |
SELECT, INSERT, UPDATE, DELETE, DDL |
executeQuery |
Executes SQL queries that return a ResultSet |
ResultSet |
SELECT |
executeUpdate |
Executes SQL queries that modify data | int (number of rows) |
INSERT, UPDATE, DELETE, DDL |