Sobes.tech
Junior

What is the difference between the execute, executeQuery, and executeUpdate methods?

sobes.tech AI

Answer from AI

executeQuery is used to execute SELECT queries and returns a ResultSet object with the results.

executeUpdate is used for executing DML commands (INSERT, UPDATE, DELETE) or DDL commands (CREATE, ALTER, DROP). It returns the number of affected rows.

execute can execute any type of SQL command. It returns a boolean: true if the result is a ResultSet, and false otherwise (if it is an update count or no result). To get the ResultSet, use getResultSet(), and to get the update count, use getUpdateCount().

Method Purpose Return Type Example SQL Commands
executeQuery SELECT ResultSet SELECT * FROM users
executeUpdate INSERT, UPDATE, DELETE, DDL int (rows affected) INSERT INTO users ..., UPDATE users ..., DROP TABLE users
execute Any type boolean Any SQL command

Example of using executeQuery:

// Getting connection
Connection conn = ...;
Statement stmt = conn.createStatement();
// Executing SELECT
ResultSet rs = stmt.executeQuery("SELECT id, name FROM users");
while (rs.next()) {
    int id = rs.getInt("id");
    String name = rs.getString("name");
    System.out.println("ID: " + id + ", Name: " + name);
}
rs.close();
stmt.close();
conn.close();

Example of using executeUpdate:

// Getting connection
Connection conn = ...;
Statement stmt = conn.createStatement();
// Executing INSERT
int updatedRows = stmt.executeUpdate("INSERT INTO users (name) VALUES ('John Doe')");
System.out.println("Inserted rows: " + updatedRows);
stmt.close();
conn.close();

Example of using execute:

// Getting connection
Connection conn = ...;
Statement stmt = conn.createStatement();
// Executing DDL
boolean isResultSet = stmt.execute("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(255))");
if (!isResultSet) {
    System.out.println("Table created or updated count: " + stmt.getUpdateCount());
}
stmt.close();
conn.close();
What is the difference between the execute… - sobes.tech