When an SQL statement is given to the server, the server parses (split the SQL statement into multiple pieces called as tokens) to analyze whether the statement is valid according to the grammar rules (syntax) of SQL. If the statement is not valid, the database server sends the information regarding the error in the statement to the client. If the statement is valid statement, the database server executes the statement.

As part of the Statement interface, we have the method executeUpdate, executeQuery. executeQuery can be used to execute the select statement and it will return a ResultSet object by which data can be fetched. executeUpdate can be used to execute non select statement and it will return a number (integer) indicates the no. of rows effected by the statement.


StatementDemo.java

/**
* A demo class to explain executeUpdate()
* @author Santhosh Reddy Mandadi
* @since 11-Jun-2012
* @version 1.0
*/

import java.sql.*;

public class StatementDemo
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:@localhost:1521:xe","scott","tiger");
String vsql1, vsql2;
vsql1 = "INSERT INTO PRODUCTS VALUES(1, 'Pen', 10.50)";
vsql2 = "INSERT INTO PRODUCTS VALUES(2, 'Pencil', 1.50)";
vsql3 = "UPDATE PRODUCTS SET PRICE = 22.50";
Statement statement = connection.createStatement();
int rows;
rows = statement.executeUpdate(vsql1);
System.out.println("No. of rows effected: "+rows);
rows = statement.executeUpdate(vsql2);
System.out.println("No. of rows effected: "+rows);
rows = statement.executeUpdate(vsql3);
System.out.println("No. of rows effected: "+rows);
}
}
1. The insert statement used in the above application inserts only one row in the PRODUCTS table. So, executeUpdate() method will return 1 indicating that insert statement has inserted one row.
2. If there are 10 rows in the PRODUCTS table, the update statement used in the application updates (modifies) all the 10 rows and the executeUpdate method returns 10.
3. If we create table SQL statement or drop table SQL statement, executeUpdate() returns 0.
4. Some of the JDBC drivers may allow passing the SELECT statement as a parameter to executeUpdate(), but it is not advisable.