In JDBC, execute(), executeQuery(), and executeUpdate() are methods to execute SQL statements. These methods have differences in terms of the type of SQL statements they can execute and the type of output or result they produce.
1. execute():
The execute() method is used to execute SQL statements that return multiple results or do not return any resultset, such as SQL statements containing conditional logic or multiple queries. This method is generally used for executing stored procedures or executing DDL statements.
Example:
String sql = "INSERT INTO students (name, age) VALUES ('John', 20)";
Statement stmt = connection.createStatement();
boolean result = stmt.execute(sql);
2. executeQuery():
The executeQuery() method is used to execute SQL SELECT statements that fetch data from the database. This method returns a ResultSet object that contains the selected data. The ResultSet object can be used to iterate through the rows of the resultset and retrieve the data from the columns.
Example:
String sql = "SELECT * FROM students WHERE age > 18";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
}
3. executeUpdate():
The executeUpdate() method is used to execute SQL statements that modify data in the database, such as INSERT, UPDATE, or DELETE statements. This method returns an integer value that represents the number of rows affected by the SQL statement.
Example:
String sql = "UPDATE students SET age = 21 WHERE name = 'John'";
Statement stmt = connection.createStatement();
int result = stmt.executeUpdate(sql);
In summary, execute() is used to execute SQL statements that do not return any resultset, executeQuery() is used to execute SQL SELECT statements that return a resultset, and executeUpdate() is used to execute SQL statements that modify data in the database.