In this tutorial, we are discuss about insert SQL statement with the jdbc batch.
In this tutorial, we are discuss about insert SQL statement with the jdbc batch.In this tutorial, we are discuss about insert SQL statement with the jdbc batch.
First of all, we will create a java class BatchInsert.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 used sequence of the step for Batch processing for data insertion in the database table.
1. Create Statement object using createStatement() method.
2. set auto commit is false using setAutoCommit().
3. Create SQL insert statement for save data in the
datasource and add these statement in batch using addBatch() method.
4. Execute the SQL statements using executeBatch() method on created statement object.
5. Last commit the connection using commit() method.
In this example we will insert data in user table in the roseindia_jdbc_tutorial database.
The code of the BatchInsert.java class is:
import java.sql.*; public class BatchInsert { 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{ Statement stmt = connection.createStatement(); // Set auto-commit to false connection.setAutoCommit(false); // insert query String insertquery1 = "INSERT INTO user (user_id, user_name) VALUES(1,'Brijesh')"; stmt.addBatch(insertquery1); // insert query String insertquery2 = "INSERT INTO user (user_id, user_name) VALUES(2,'Raj')"; stmt.addBatch(insertquery2); // insert query String insertquery3 = "INSERT INTO user (user_id, user_name) VALUES(3,'Ankit')"; stmt.addBatch(insertquery3); stmt.executeBatch(); System.out.println("Batch Insert 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 console output is:
The database table output is: