Executing a Query
A simple database transaction uses only one of the three execution methods in the Statement
Interface:
public ResultSet executeQuery( String sql ) throws SQLException
It executes an SQL statement that returns a single ResultSet
object.
This method should be used for any SQL calls that expect to return data from the database. For example,
ResultSet rset = stmt.executeQuery(
"SELECT ename FROM emp" );
public int executeUpdate( String sql ) throws SQLException
It executes an SQL INSERT
, UPDATE
, or DELETE
statement.
In addition, SQL statements that return nothing, such as SQL DDL statements, can be executed.
This method returns the number of affected rows. For example,
stmt.executeUpdate ( "insert into customers values (
'Pokemon', '123456789', 0 )" );
public boolean execute( String sql ) throws SQLException
It is for situations in which you do not know whether the SQL being executed is a query or update. For example,
try {
stmt.execute( "drop table people" );
stmt.execute( "drop type PERSON FORCE" );
stmt.execute( "drop type ADDRESS FORCE" );
}
catch ( SQLException e ) {
System.out.println( e );
}
†This usually happens when the application is executing dynamically created SQL statements.