JDBC Batch Update Example


 

JDBC Batch Update Example

In this JDBC tutorial you will learn how to update data in batch.

In this JDBC tutorial you will learn how to update data in batch.

Batch Update Example

You can update data in a table batch. To update in batch at first you need set connection autoCommit fale mode then add the query string in batch as

String updateQuery1 = "INSERT INTO student VALUES(4,'Raman','B.Tech','Betiah')";
statement.addBatch(updateQuery1);

and finally commit the connection. An example of batch update is given below

 

BatchupdateExample.java

package roseindia.net;

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

public class BatchupdateExample {
	Connection connection = null;
	static int roll;

	public BatchupdateExample() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
		}
	}

	public Connection getConnection() throws SQLException {
		connection = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/student", "root", "root");

		return connection;
	}

	public static void main(String[] args) throws Exception {
		BatchupdateExample updateableResultSet = new BatchupdateExample();
		Connection conn = updateableResultSet.getConnection();
		Statement statement = conn.createStatement(
				ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		conn.setAutoCommit(false);
		String updateQuery1 = "INSERT INTO student VALUES(12,'Raman','B.Tech','Betiah')";
		statement.addBatch(updateQuery1);
		String updateQuery2 = "INSERT INTO student VALUES(13,'Kanhaiya','M.Tech','Delhi')";
		statement.addBatch(updateQuery2);
		String updateQuery3 = "INSERT INTO student VALUES(14,'Tinkoo','MBA','Alligarh')";
		statement.addBatch(updateQuery3);
		String updateQuery4 = "INSERT INTO student VALUES(11,'Pawan','BBA','Darbhanga')";
		statement.addBatch(updateQuery4);
		statement.executeBatch();
		String query = "SELECT * FROM student";
		ResultSet rs = statement.executeQuery(query);
		conn.commit();
		while (rs.next()) {
			System.out.println(rs.getInt(1) + ":" + rs.getString(2) + ":"
					+ rs.getString(3) + ":" + rs.getString(4));
		}
		rs.close();
		statement.close();
		conn.close();
	}
}
When you run this application it will display message as shown below:

1:Java:MCA:Motihari
2:Ravi:BCA:Patna
3:Mansukh:M.Sc:Katihar
4:Raman:B.Tech:Betiah
5:Kanhaiya:M.Tech:Delhi
6:Tinkoo:MBA:Alligarh
7:Pawan:BBA:Darbhanga
8:Ram:BCA:Patna
9:Data Structures:Program:LaheriaSarai
11:Pawan:BBA:Darbhanga
12:Raman:B.Tech:Betiah
13:Kanhaiya:M.Tech:Delhi
14:Tinkoo:MBA:Alligarh

Download this example code

Ads