Share on Google+Share on Google+

JDBC Batch executeBatch() Method Example

Advertisement
In this example, we can evaluate executebatch() method of the jdbc batch processing.

JDBC Batch executeBatch() Method Example:

In this example, we can evaluate executebatch() method of the jdbc batch processing. The executebatch() method are use to execute the batch on the statement.

Syntax:

statement.executeBatch();

In the syntax, statement is the object of the Statement class. The executeBatch() method  execute all the SQL statements on created statement object.

In this example, we are discuss with SQL delete statement with batch. We are create connection with the data source as:

Connection connection = null;

Class.forName("com.mysql.jdbc.Driver");

connection = DriverManager.getConnection(
           
"jdbc:mysql://localhost:3306/roseindia_jdbc_tutorials",
            "root"
,"
root");

Now we will create statement and set auto commit false as:

Statement stmt = connection.createStatement();

connection.setAutoCommit(false);

Now we will create SQL statement and add this statement in the batch as:

String insertquery1 = "Delete from user where user_id=3";

stmt.addBatch(insertquery1);

Now execute this batch by using executeBatch() method on the created statement object as:

stmt.executeBatch();

The code of the executebatch() example is:

import java.sql.*;
public class BatchExecuteBatch {  
  public static void main(String[] args) {
     try{
    Connection connection = null;
    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection(
          
"jdbc:mysql://localhost:3306/roseindia_jdbc_tutorial",
            "root"
,"root");
    try{            
     // Create statement object  
     Statement stmt = connection.createStatement();            
     // Set auto-commit to false
     connection.setAutoCommit(false);
     // insert query 
     String insertquery1 = "Delete from user where user_id=3";              
     stmt.addBatch(insertquery1);
       stmt.executeBatch();
       System.out.println("Batch executeBatch() example." );
       // connection commited
       connection.commit();
      }
    catch (SQLException s){
       System.out.println("SQL Exception " + s);
    }
   }
   catch (Exception e){
      e.printStackTrace();
   }
   }
}

Now run this example on eclipse IDE and see the output.

This eclipse console output is:

The database table output is:

Download code

Advertisements

Advertisement

Posted on: October 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.