JDBC – Batch Processing Tutorial with Example

In this tutorial you will learn

1. What is Batch Processing in JDBC?
2. How to Batch Processing in JDBC?
3. Methods and Programming Example

What is Batch Processing in JDBC?

The word “Batch Processing” tells everything itself by its name. Process of executing multiple queries at once is called Batch Processing. Batch Processing makes the performance fast and efficient, that executes multiple sql statements quickly. JDBC Batch Processing provides method for implementing bulk query execution.

Methods

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

Programming Example

package AdvanceJDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class BatchProcessing_Example
{
	   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
	   static final String dburl = "jdbc:mysql://localhost/STOREDB";	   
	   static final String dbuser = "root";
	   static final String dbpass = "root";
	   
public static void main(String[] args) throws SQLException
{
	Connection con = null;
	Statement stmt = null;
	
	try 
	{
	    //Step 1 : Connecting to server and database
	    con = DriverManager.getConnection(dburl, dbuser, dbpass);
	    con.setAutoCommit(false);
	    
	    //Step 2 : Initialize Statement
	    stmt=con.createStatement();
	    
	    //Step 3 : SQL Query
	    String query1="INSERT INTO ITEM(PRODUCT,PRICE) VALUES('Keyboard','770')";
	    String query2="INSERT INTO ITEM(PRODUCT,PRICE) VALUES('WebCam','1150')";
	    String query3="INSERT INTO ITEM(PRODUCT,PRICE) VALUES('HardDrive','3800')";
	    String query4="INSERT INTO ITEM(PRODUCT,PRICE) VALUES('Printer','12000')";
	    String query5="INSERT INTO ITEM(PRODUCT,PRICE) VALUES('Bluetooth','220')";
	    
	    //Step 4 : Adding query to Batch
	    stmt.addBatch(query1);
	    stmt.addBatch(query2);
	    stmt.addBatch(query3);
	    stmt.addBatch(query4);
	    stmt.addBatch(query5);
	    
	    //Step 5 : Execute Batch
	    stmt.executeBatch();
	   
	    con.commit();
	    System.out.println("Batch Update Successful");
	    
	} 
	
	catch (SQLException e) 
	{
	    System.err.println("Cannot connect ! ");
	    con.rollback();
	    e.printStackTrace();
	}
	
	finally {
	    System.out.println("Closing the connection.");
	    if (con != null) try { con.close(); } catch (SQLException ignore) {}
	}
	
}
}

Output:
Batch Update Successful
Closing the connection.


Summary

In this tutorial you learned how to use Batch Processing in JDBC. The programming example explains this concept clearly. In the next chapter you will learn about Store Procedure in JDBC.


Leave a Reply

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