Tuesday, January 25, 2022

"java.sql.PreparedStatment" and Batch in JDBC

 java.sql.PreparedStatment:-


  • It is an interface which is a part of JDBC API, and its implementation are provided by respective DB server or vendors as a part of JDBC Driver.

  •  PreparedStatment interface is a sub-interface of Statement interface.

  •  It supports the concept of PlaceHolder.

  • It supports the concept of Execution Plan( Compile once execute many times ).

  •  In case of PreparedStatement, the query is passed at the time of implementation object creation of PreparedStatement interface.

  •   Hence, PreparedStatement are also known as Pre-compiled Statement.


 Syntax:-

         java.sql.PreparedStatement pstmt = con.prepareStatement("Query");


  • prepareStatement() is a factory or helper method which creates and return the implementation object of PreparedStatement interface.

  •  Hence, the return type for prepareStatement() is PreparedStatement interface.


Note[JOB]:-

  • Since Compilation takes place each time along with Execution whenever we execute query using Statement Interface, Performance of an application decreases.

  •    Hence, it is a good practice to make use of PreparedStatement interface to deal with multiple records.


  Statement interface:-

    Statement stmt = con.createStatement(); 

    stmt.executeUpdate("Qry"); // Complication and Execution 

    stmt.executeUpdate("Qry"); 


 PreparedStatement interface:-

   PreparedStatement pstmt=con.prepareStatement("Qry"); // pass the qry while creating a platform

   pstmt.executeUpdate();

   pstmt.execcuteUpdate();


Batch Update:-

Batch:- it is a collection of only DML Query.


Need of Batch:- Batch Update is needed to make one single data base call and affect multiple records of multiple tables at once.


Advantage:- Batch Update greatly improves the performance of an application.


Batch Update is applicable only for DML Queries.

  • In case of Batch Update after adding all the DML Queries into the Batch, the entire Batch will execute only once.

 There are 2 methods w.r.t Batch.

   a) addBatch()      b) executeBatch()


a) addBatch():-

  •  This is used to add all the DML Queries into the Batch.


b) executeBatch():-

  •  This method is used to execute all the DML Queries present inside the Batch only once by making one single DB call.

  • It returns an integer Array.

  •  The size of the integer Array represents the total no of DML Queries added into the Batch.


Note:-

  • Whenever we use a Batch with Statement interface, then one single batch can contain all types of DML Queries in it.

  • Whenever we use Batch with PreparedStatement interface, then one single batch can contain only one DML Query in it.

  •   Hence, Batch with Statement interface is faster in Performance.

0 comments:

If you have any doubts,please let me know