Junior — Middle
What are the differences between the execute, executeQuery, and executeUpdate methods when working with a database?
sobes.tech AI
Answer from AI
In Java, when working with JDBC:
-
executeQuery(String sql)— used to execute SQL queries that return data (usuallySELECT). Returns aResultSetobject. -
executeUpdate(String sql)— used for SQL commands that modify data (e.g.,INSERT,UPDATE,DELETE) or table structures (CREATE,DROP). Returns the number of affected rows. -
execute(String sql)— a versatile method that can execute any SQL query. Returnstrueif the result is aResultSet, andfalseif it is an update count or no result. To get the result, you need to callgetResultSet()orgetUpdateCount().
Example:
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
int rows = stmt.executeUpdate("UPDATE users SET active = 1 WHERE id = 10");
boolean hasResultSet = stmt.execute("SELECT * FROM users");
if (hasResultSet) {
ResultSet rs2 = stmt.getResultSet();
// process rs2
} else {
int updateCount = stmt.getUpdateCount();
// process updateCount
}