Hi All,

Greeting of the day!

Today we will be exploring Statement, PreparedStatment & CallableStatement in java.

So let's start.

Statement, PreparedStatment & CallableStatement all interface of java.sql  

So when to use which of the above interfaces?

  • Statement -- is used when we want to execute static queries without any dynamic values.
  • PreparedStatement-- extends Statement and is basically used when we want to execute dynamic query/parameterize query in which we have to pass parameters at run time.
    • A prepared statement is used when we are executing the same query multiple times, it's recommended over Statement in such a scenario because the performance of PreparedStatement is high as a query is already precompiled a query plan is generated only once. After subsequent execution use the same query plan.
  • CallableStatement--extends PreparedStatment & is used to call stored procedures and functions.

Statement

How to execute a query using Statement in java?

We need to follow 3 steps.
  • Load driver & create an instance of Connection.
  • Get an instance of a Statement using Connection.
  • Execute the query using Statement.
Example



PreparedStatment

How to execute the query using PreparedStatment

We need to follow 4 steps.
  • Load driver & create an instance of Connection.
  • Create PreparedStatement instance & SQL Query.
  • Replace parameters with dynamic values.
  • Execute query.
Example



So here you can see we are placing? for input parameters and later we will set this parameter before executing the query.


CallableStatement

CallableStatement is used to execute stored procedures or functions. We can pass IN & OUT parameters in callable statements which are used in the procedure.

Let's take the example of the below procedure.   



How to call stored procedure using CallableStatement in java

Below are the steps we need to follow for using CallableStatement.
  • Load driver & create an instance of Connection.
  • Create CallableStatement instance & with a call to the stored procedure.
  • Register IN & OUT parameters.
  • Execute call.
  • Fetch output parameter
So here we need to register 2 IN parameters & 1 OUT parameter. Below is code how to use CallableStatement to call the above procedure

 
So we have explored all three interfaces. Let me know if you have any questions.

You can refer below useful post





Thanks
Happy Learning!