Skip to main content

JDBC: Transaction Management, Batch Processing & Row Set

Transaction Management in JDBC

Transaction represents a single unit of work.

The ACID properties describes the transaction management well. ACID stands for Atomicity, Consistency, isolation and durability.

Atomicity means either all successful or none.

Consistency ensures bringing the database from one consistent state to another consistent state.

Isolation ensures that transaction is isolated from other transaction.

Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc.


Advantage of Transaction Mangaement

fast performance It makes the performance fast because database is hit at the time of commit.


transaction management in jdbc

In JDBC, Connection interface provides methods to manage transaction.

MethodDescription
void setAutoCommit(boolean status)It is true bydefault means each transaction is committed bydefault.
void commit()commits the transaction.
void rollback()cancels the transaction.

Simple example of transaction management in jdbc using Statement

Let's see the simple example of transaction management using Statement.

  1. import java.sql.*;  
  2. class FetchRecords{  
  3. public static void main(String args[])throws Exception{  
  4. Class.forName("oracle.jdbc.driver.OracleDriver");  
  5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  6. con.setAutoCommit(false);  
  7.   
  8. Statement stmt=con.createStatement();  
  9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");  
  10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");  
  11.   
  12. con.commit();  
  13. con.close();  
  14. }}  

If you see the table emp400, you will see that 2 records has been added.

Example of transaction management in jdbc using PreparedStatement

Let's see the simple example of transaction management using PreparedStatement.

  1. import java.sql.*;  
  2. import java.io.*;  
  3. class TM{  
  4. public static void main(String args[]){  
  5. try{  
  6.   
  7. Class.forName("oracle.jdbc.driver.OracleDriver");  
  8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  9. con.setAutoCommit(false);  
  10.   
  11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");  
  12.   
  13. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  14. while(true){  
  15.   
  16. System.out.println("enter id");  
  17. String s1=br.readLine();  
  18. int id=Integer.parseInt(s1);  
  19.   
  20. System.out.println("enter name");  
  21. String name=br.readLine();  
  22.   
  23. System.out.println("enter salary");  
  24. String s3=br.readLine();  
  25. int salary=Integer.parseInt(s3);  
  26.   
  27. ps.setInt(1,id);  
  28. ps.setString(2,name);  
  29. ps.setInt(3,salary);  
  30. ps.executeUpdate();  
  31.   
  32. System.out.println("commit/rollback");  
  33. String answer=br.readLine();  
  34. if(answer.equals("commit")){  
  35. con.commit();  
  36. }  
  37. if(answer.equals("rollback")){  
  38. con.rollback();  
  39. }  
  40.   
  41.   
  42. System.out.println("Want to add more records y/n");  
  43. String ans=br.readLine();  
  44. if(ans.equals("n")){  
  45. break;  
  46. }  
  47.   
  48. }  
  49. con.commit();  
  50. System.out.println("record successfully saved");  
  51.   
  52. con.close();//before closing connection commit() is called  
  53. }catch(Exception e){System.out.println(e);}  
  54.   
  55. }}  

It will ask to add more records until you press n. If you press n, transaction is committed.

Batch Processing in JDBC

Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast.

The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.

Advantage of Batch Processing

Fast Performance


Methods of Statement interface

The required methods for batch processing are given below:

MethodDescription
void addBatch(String query)It adds query into batch.
int[] executeBatch()It executes the batch of queries.

Example of batch processing in jdbc

Let's see the simple example of batch processing in jdbc. It follows following steps:

  • Load the driver class
  • Create Connection
  • Create Statement
  • Add query in the batch
  • Execute Batch
  • Close Connection
  1. import java.sql.*;  
  2. class FetchRecords{  
  3. public static void main(String args[])throws Exception{  
  4. Class.forName("oracle.jdbc.driver.OracleDriver");  
  5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  6. con.setAutoCommit(false);  
  7.   
  8. Statement stmt=con.createStatement();  
  9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");  
  10. stmt.addBatch("insert into user420 values(191,'umesh',50000)");  
  11.   
  12. stmt.executeBatch();//executing the batch  
  13.   
  14. con.commit();  
  15. con.close();  
  16. }}  

If you see the table user420, two records has been added.

Example of batch processing using PreparedStatement

  1. import java.sql.*;  
  2. import java.io.*;  
  3. class BP{  
  4. public static void main(String args[]){  
  5. try{  
  6.   
  7. Class.forName("oracle.jdbc.driver.OracleDriver");  
  8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  9.   
  10. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");  
  11.   
  12. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  13. while(true){  
  14.   
  15. System.out.println("enter id");  
  16. String s1=br.readLine();  
  17. int id=Integer.parseInt(s1);  
  18.   
  19. System.out.println("enter name");  
  20. String name=br.readLine();  
  21.   
  22. System.out.println("enter salary");  
  23. String s3=br.readLine();  
  24. int salary=Integer.parseInt(s3);  
  25.   
  26. ps.setInt(1,id);  
  27. ps.setString(2,name);  
  28. ps.setInt(3,salary);  
  29.   
  30. ps.addBatch();  
  31. System.out.println("Want to add more records y/n");  
  32. String ans=br.readLine();  
  33. if(ans.equals("n")){  
  34. break;  
  35. }  
  36.   
  37. }  
  38. ps.executeBatch();  
  39.   
  40. System.out.println("record successfully saved");  
  41.   
  42. con.close();  
  43. }catch(Exception e){System.out.println(e);}  
  44.   
  45. }}  

It will add the queries into the batch until user press n. Finally it executes the batch. Thus all the added queries will be fired.

JDBC RowSet

The instance of RowSet is the java bean component because it has properties and java bean notification mechanism. It is introduced since JDK 5.

It is the wrapper of ResultSet. It holds tabular data like ResultSet but it is easy and flexible to use.

The implementation classes of RowSet interface are as follows:

  • JdbcRowSet
  • CachedRowSet
  • WebRowSet
  • JoinRowSet
  • FilteredRowSet
Java Rowset

Let's see how to create and execute RowSet.

  1. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();  
  2. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");  
  3. rowSet.setUsername("system");  
  4. rowSet.setPassword("oracle");  
  5.            
  6. rowSet.setCommand("select * from emp400");  
  7. rowSet.execute();  

It is the new way to get the instance of JdbcRowSet since JDK 7.

Advantage of RowSet

The advantages of using RowSet are given below:

  1. It is easy and flexible to use
  2. It is Scrollable and Updatable bydefault

Simple example of JdbcRowSet

Let's see the simple example of JdbcRowSet without event handling code.

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.ResultSet;  
  4. import java.sql.Statement;  
  5. import javax.sql.RowSetEvent;  
  6. import javax.sql.RowSetListener;  
  7. import javax.sql.rowset.JdbcRowSet;  
  8. import javax.sql.rowset.RowSetProvider;  
  9.   
  10. public class RowSetExample {  
  11.         public static void main(String[] args) throws Exception {  
  12.                  Class.forName("oracle.jdbc.driver.OracleDriver");  
  13.       
  14.     //Creating and Executing RowSet  
  15.         JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();  
  16.         rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");  
  17.         rowSet.setUsername("system");  
  18.         rowSet.setPassword("oracle");  
  19.                    
  20.         rowSet.setCommand("select * from emp400");  
  21.         rowSet.execute();  
  22.                    
  23.     while (rowSet.next()) {  
  24.                         // Generating cursor Moved event  
  25.                         System.out.println("Id: " + rowSet.getString(1));  
  26.                         System.out.println("Name: " + rowSet.getString(2));  
  27.                         System.out.println("Salary: " + rowSet.getString(3));  
  28.                 }  
  29.                  
  30.         }  
  31. }  

The output is given below:

Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000

Full example of Jdbc RowSet with event handling

To perform event handling with JdbcRowSet, you need to add the instance of RowSetListener in the addRowSetListener method of JdbcRowSet.

The RowSetListener interface provides 3 method that must be implemented. They are as follows:

1) public void cursorMoved(RowSetEvent event);
2) public void rowChanged(RowSetEvent event);
3) public void rowSetChanged(RowSetEvent event);

Let's write the code to retrieve the data and perform some additional tasks while cursor is moved, cursor is changed or rowset is changed. The event handling operation can't be performed using ResultSet so it is preferred now.

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.ResultSet;  
  4. import java.sql.Statement;  
  5. import javax.sql.RowSetEvent;  
  6. import javax.sql.RowSetListener;  
  7. import javax.sql.rowset.JdbcRowSet;  
  8. import javax.sql.rowset.RowSetProvider;  
  9.   
  10. public class RowSetExample {  
  11.         public static void main(String[] args) throws Exception {  
  12.                  Class.forName("oracle.jdbc.driver.OracleDriver");  
  13.       
  14.     //Creating and Executing RowSet  
  15.     JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();  
  16.     rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");  
  17.     rowSet.setUsername("system");  
  18.     rowSet.setPassword("oracle");  
  19.                    
  20.         rowSet.setCommand("select * from emp400");  
  21.         rowSet.execute();  
  22.                    
  23.     //Adding Listener and moving RowSet  
  24.     rowSet.addRowSetListener(new MyListener());  
  25.   
  26.                  while (rowSet.next()) {  
  27.                         // Generating cursor Moved event  
  28.                         System.out.println("Id: " + rowSet.getString(1));  
  29.                         System.out.println("Name: " + rowSet.getString(2));  
  30.                         System.out.println("Salary: " + rowSet.getString(3));  
  31.                 }  
  32.                  
  33.         }  
  34. }  
  35.   
  36. class MyListener implements RowSetListener {  
  37.       public void cursorMoved(RowSetEvent event) {  
  38.                 System.out.println("Cursor Moved...");  
  39.       }  
  40.      public void rowChanged(RowSetEvent event) {  
  41.                 System.out.println("Cursor Changed...");  
  42.      }  
  43.      public void rowSetChanged(RowSetEvent event) {  
  44.                 System.out.println("RowSet changed...");  
  45.      }  
  46. }  

The output is as follows:

Cursor Moved...
Id: 55
Name: Om Bhim
Salary: 70000
Cursor Moved...
Id: 190
Name: abhi
Salary: 40000
Cursor Moved...
Id: 191
Name: umesh
Salary: 50000
Cursor Moved...



Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&