Batch update using PreparedStatement JDBC

The JDBC PreparedStatement is used to execute parameterized queries against the database. Let us study JDBC PreparedStatement by batch update example.

Example:

JDBCTest.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import com.w3spoint.util.JDBCUtil;
 
/**
 * This class is used to batch update in DB table
 * using PreparedStatement.
 * @author w3spoint
 */
public class JDBCTest {
	public static void main(String args[]){
		Connection conn = null;
		PreparedStatement preparedStatement = null;
 
		String query = "insert into EMPLOYEE " +
			"(EMPLOYEE_ID, NAME, SALARY) " +
			"values (?,?,?)";
 
		try{			
			//get connection
			conn = JDBCUtil.getConnection();
 
			//set auto commit to false
			conn.setAutoCommit(false);
 
			//create preparedStatement
			preparedStatement = conn.prepareStatement(query);
 
			//set values
			preparedStatement.setInt(1, 1);
			preparedStatement.setString(2, "Bharat");
			preparedStatement.setInt(3, 62000);
			preparedStatement.addBatch();
 
			//set values
			preparedStatement.setInt(1, 4);
			preparedStatement.setString(2, "Bharti");
			preparedStatement.setInt(3, 52000);
			preparedStatement.addBatch();
 
			//execute query
			preparedStatement.executeBatch();
 
			//commit
			conn.commit();
 
			//close connection
			preparedStatement.close();
			conn.close();
 
		     System.out.println("Record inserted successfully.");
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
}

JDBCUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
 
/**
 * This is a utility class for JDBC connection.
 * @author w3spoint
 */
public class JDBCUtil {
	//JDBC and database properties.
	private static final String DB_DRIVER = 
		           "oracle.jdbc.driver.OracleDriver";
	private static final String DB_URL = 
		        "jdbc:oracle:thin:@localhost:1521:XE";
	private static final String DB_USERNAME = "system";
	private static final String DB_PASSWORD = "oracle";
 
	public static Connection getConnection(){
		Connection conn = null;
		try{
			//Register the JDBC driver
			Class.forName(DB_DRIVER);
 
			//Open the connection
			conn = DriverManager.
			getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
 
			if(conn != null){
			   System.out.println("Successfully connected.");
			}else{
			   System.out.println("Failed to connect.");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}	
}

Output:

Successfully connected.
Record inserted successfully.

Download this example.   Next Topic: JDBC CallableStatement interface. Previous Topic: JDBC PreparedStatement deletes a record example.

 

Please follow and like us:
Content Protection by DMCA.com