Transaction Management and Batch Processing in JDBC

Last updated on Dec 29 2022
Prabhas Ramanathan

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.

Table of Contents

Advantage of Transaction Mangaement

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

 

java 126

In JDBC, Connection interface provides methods to manage transaction.

 

Method Description
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:
Method Description
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.
So, this brings us to the end of blog. This Tecklearn ‘Transaction Management and Batch Processing in JDBC’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Transaction Management and Batch Processing in JDBC"

Leave a Message

Your email address will not be published. Required fields are marked *