Share on Google+Share on Google+

JDBC Batch Example With SQL Update Statement

Advertisement
In this tutorial, we are discuss about update SQL statement with the jdbc batch.

JDBC Batch Example With SQL Update Statement:

In this tutorial, we are discuss about update SQL statement with the jdbc batch.

Now we will create a java class BatchUpdate.java.

In this class we will create database connection as:

Connection connection = null;

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

connection = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/databasename","username","passsword");

Now we will create Statement object by using createStatement() method and Connection object as:

Statement stmt = connection.createStatement();

Now we set auto commit false using setAutoCommit() method as:

connection.setAutoCommit(false);

Now we will create SQL query and add in to the batch as:

String updatequery1 = "UPDATE user SET user_name = 'Ravi' WHERE user_id = 1";

stmt.addBatch(updatequery1);

Now we will execute batch on the Statement object as:

stmt.executeBatch();

And last commit the connection as:

connection.commit();

This is the step sequence of the batch processing with update statement.

The code of the BatchUpdate.java is:

import java.sql.*;
public class BatchUpdate {
  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);
        // Update query
        String updatequery1 = "UPDATE user SET user_name = 'Ravi' WHERE user_id = 1";
        stmt.addBatch(updatequery1);
        // Update query
        String updatequery2 = "UPDATE user SET user_name = 'Brijesh' WHERE user_id = 2";
        stmt.addBatch(updatequery2);
        stmt.executeBatch();
        System.out.println("Batch Update Processing is done successfully." );
          // connection commited
        connection.commit();
      }
      catch (SQLException s){
         System.out.println("SQL Exception " + s);
       }
     }
     catch (Exception e){
        e.printStackTrace();
    }  
      }
  }

 Now we will run this example on eclipse and see the output.

Program output:

The eclipse console output is:

The database table output is:

Download Code

Advertisements

Advertisement

Posted on: October 14, 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.