by BehindJava

What is statement, prepared statement and callable statement in JDBC and Why are they used

Home » java » What is statement, prepared statement and callable statement in JDBC and Why are they used

In this tutorial we are going to learn about statement, prepared statement and callable statement in JDBC and Why are they used in detail.

Statement

The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

The important methods of Statement interface are as follows:

  • public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.
  • public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.
  • public boolean execute(String sql): is used to execute queries that may return multiple results.
  • public int[] executeBatch(): is used to execute batch of commands.

Prepared statement

The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query. Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.

Let’s see the example of parameterized query:

String sqlQuery="insert into employee values(?,?,?)";  

The important methods of Statement interface are as follows:

  • public void setInt(int paramIndex, int value): sets the integer value to the given parameter index.
  • public void setString(int paramIndex, String value): sets the String value to the given parameter index.
  • public void setFloat(int paramIndex, float value): sets the float value to the given parameter index.
  • public void setDouble(int paramIndex, double value): sets the double value to the given parameter index.
  • public int executeUpdate():executes the query. It is used for create, drop, insert, update, delete etc.
  • public ResultSet executeQuery(): executes the select query. It returns an instance of ResultSet.

Callable statement

CallableStatement interface is used to call the stored procedures and functions.

Suppose you need the get the age of the employee based on the date of birth, you may create a function that receives date as the input and returns age of the employee as the output.