Interview question
What is the difference between execute(), executeQuery(), and executeUpdate() in JDBC? JDBC में execute(), executeQuery(), और executeUpdate() में क्या अंतर है?
Answer
| Method | Used for | Return type |
|---|---|---|
| executeQuery() | SELECT statements only | ResultSet |
| executeUpdate() | INSERT, UPDATE, DELETE, DDL statements | int (number of rows affected) |
| execute() | Any SQL statement, when the type is unknown beforehand | boolean (true if result is a ResultSet) |
Statement stmt = conn.createStatement();
// executeQuery() - for SELECT, returns rows
ResultSet rs = stmt.executeQuery('SELECT * FROM users');
while (rs.next()) {
System.out.println(rs.getString('name'));
}
// executeUpdate() - for INSERT/UPDATE/DELETE, returns affected row count
int rowsInserted = stmt.executeUpdate(
"INSERT INTO users (name, email) VALUES ('John', 'john@example.com')");
System.out.println(rowsInserted + ' row(s) inserted');
int rowsUpdated = stmt.executeUpdate(
"UPDATE users SET name = 'Jane' WHERE id = 1");
System.out.println(rowsUpdated + ' row(s) updated');
// execute() - generic, used when statement type isn't known ahead of time
boolean isResultSet = stmt.execute('SELECT * FROM users');
if (isResultSet) {
ResultSet result = stmt.getResultSet();
} else {
int updateCount = stmt.getUpdateCount();
}
// Using execute() for statements that could be either (e.g. stored procedures)
boolean hasResults = stmt.execute('{call processOrder(1)}');
// Common mistake: using executeQuery() for an INSERT statement
// stmt.executeQuery('INSERT INTO users ...'); // SQLException: not a SELECT| Method | किसके लिए | Return type |
|---|---|---|
| executeQuery() | सिर्फ SELECT | ResultSet |
| executeUpdate() | INSERT, UPDATE, DELETE, DDL | int (affected rows) |
| execute() | कोई भी SQL, type अनजान होने पर | boolean |
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery('SELECT * FROM users');
while (rs.next()) {
System.out.println(rs.getString('name'));
}
int rowsInserted = stmt.executeUpdate(
"INSERT INTO users (name, email) VALUES ('John', 'john@example.com')");
System.out.println(rowsInserted + ' row(s) inserted');
int rowsUpdated = stmt.executeUpdate(
"UPDATE users SET name = 'Jane' WHERE id = 1");
boolean isResultSet = stmt.execute('SELECT * FROM users');
if (isResultSet) {
ResultSet result = stmt.getResultSet();
} else {
int updateCount = stmt.getUpdateCount();
}
// गलती: INSERT के लिए executeQuery() use करना
// stmt.executeQuery('INSERT INTO users ...'); // SQLExceptionWas this answer clear?