JDBC- Batch Processing

Batch Processing

Instead of executing a single query, we can execute a group of queries.The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing

  • void addBatch(String query) It adds query into batch.

  • int[] executeBatch() It executes the batch of queries.

Statement stmt=con.createStatement();  
stmt.addBatch("insert into user420 values(190,'abhi',40000)");  
stmt.addBatch("insert into user420 values(191,'umesh',50000)");    
stmt.executeBatch();//executing the batch


public class JDBC {
	public static void main(String[] args) throws Exception {
 String url = "jdbc:mysql://localhost:3306/mydb";
 String u = "root";
 String p = "123456";
 PreparedStatement ps = null;
 Class.forName("com.mysql.jdbc.Driver");
 Connection con = DriverManager.getConnection(url, u, p);
 Statement st = con.createStatement();
 st.addBatch("insert into  student	 values(81, 'Syam', 'mtm')");
 st.addBatch("insert into  student	 values(11, 'ram', 'mum')");
 st.addBatch("insert into  student	 values(14, 'bam', 'kuk')");
 st.addBatch("insert into  student	 values(44, 'pram', 'sec')");

 int rs[] = st.executeBatch();
 int sum = 0;
 for (int i = 0; i < rs.length; i++) {
 	sum = sum + i;
 }
 System.out.println(sum + "Record are UPDATED using BATCH");
	}
}