Sobes.tech
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 (usually SELECT). Returns a ResultSet object.

  • 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. Returns true if the result is a ResultSet, and false if it is an update count or no result. To get the result, you need to call getResultSet() or getUpdateCount().

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
}
What are the differences between the execute… - sobes.tech