Sobes.tech
Junior — Middle

What are the differences between execute, executeQuery, and executeUpdate methods in JDBC, and when should each be used?

sobes.tech AI

Answer from AI

In JDBC, the methods execute, executeQuery, and executeUpdate have different purposes:

  • executeQuery() — used to execute SQL queries that return a result set (SELECT). Returns a ResultSet object.

  • executeUpdate() — used to execute SQL commands that modify data or database structure (INSERT, UPDATE, DELETE, DDL). Returns the number of affected rows.

  • execute() — a universal method that can execute any SQL statement. Returns a boolean: true if the result is a ResultSet, false if it is an update count.

When to use:

  • For data retrieval — executeQuery.
  • For data or structure modification — executeUpdate.
  • If the query type is unknown in advance or can vary — execute.

Example:

String sql = "SELECT * FROM users";
ResultSet rs = statement.executeQuery(sql);

String updateSql = "UPDATE users SET name='John' WHERE id=1";
int rows = statement.executeUpdate(updateSql);

boolean hasResultSet = statement.execute(sql);
if (hasResultSet) {
    ResultSet rs2 = statement.getResultSet();
    // processing
}