JDBC Statement Example – Batch Insert, Update, Delete

When you have a lot of insert or update sql commands to execute, you can use java.sql.Statement addBatch(String sqlCmd) method to group them together and then run java.sql.Statement executeBatch() to commit all the commands to the database server at once.

Notes Of  JDBC Batch Operation

  1. Enhance database communication performance because sql commands was sent to database server by group, this can reduce the cost of communication between client and server.
  2. Batch operation is a feature of target database server, it is not required by jdbc driver. You can use Connection.getMetaData().supportsBatchUpdates() to check whether the destination database support batch update or not.
  3. Batch operation can be used to not only insert command but also update and delete commands as well.
  4. You should use java.sql.Connection.setAutoCommit(false) to disable database auto commit before execute batch db actions.
  5. After execute batch operations, use java.sql.Connection.commit() to commit the operations to database server at once.
  6. You should run java.sql.Connection.setAutoCommit(true) to enable auto commit for later db operations.
  7. Batched sql can operate multiple tables.

Batch SQL Code Snippets

	/* Get connection object. */
	Connection dbConn = this.getMySqlConnection(ip, port, dbName, userName, password);
	/* Disable auto commit. */
	/* Get statement object. */
	Statement stmt = dbConn.createStatement();
    /* Add sql in batch, each sql can operate different table. */		

	/* Execute batch sql to db server. */
	int updateCountArr[] = stmt.executeBatch();
    /* Do not forget commit. */		
    /* Enable auto commit for later db operation. */		

Complete Example Codes

Below example will use mysql database, insert and update data to table teacher and student in batch. You can refer to How To Use JDBC To Connect MySql Database to learn more about JDBC MySQL.

mysql table teahcer created in phpMyAdmin

	public void testBatchUpdate(String ip, int port, String dbName, String userName, String password)
		String sqlArr[] = new String[6];
		sqlArr[0] = "insert into student values('richard','[email protected]')";
		sqlArr[1] = "insert into student values('jerry','[email protected]')";
		sqlArr[2] = "insert into teacher(name, email) values('tom','[email protected]')";
		sqlArr[3] = "update teacher set email = '[email protected]' where name = 'hello'";
		sqlArr[4] = "insert into teacher(name, email) values('song','[email protected]')";
		sqlArr[5] = "insert into teacher(name, email) values('jerry','[email protected]')";
		this.executeBatchSql(ip, port, dbName, userName, password, sqlArr);
	/* Batch execute insert, update, delete commands. */
	public void executeBatchSql(String ip, int port, String dbName, String userName, String password, String sqlArr[])
		/* Declare the connection and statement object. */
		Connection dbConn = null;
		Statement stmt = null;
			/* Get connection object. */
			dbConn = this.getMySqlConnection(ip, port, dbName, userName, password);
			/* Check whether this db support batch update or not. */
			boolean supportBatch = dbConn.getMetaData().supportsBatchUpdates();
				System.out.println("This database support batch update.");
				System.out.println("This database do not support batch update.");
			/* Disable auto commit. */
			/* Get statement object. */
			stmt = dbConn.createStatement();
				int len = sqlArr.length;
				for(int i=0;i<len;i++) { String sql = sqlArr[i]; stmt.addBatch(sql); System.out.println("Batch add sql : " + sql); } if(len > 0)
					/* The return array save each command updated rows number. */
					int updateCountArr[] = stmt.executeBatch();
					System.out.println("Execute batch sql successfully. ");
					int updateLength = updateCountArr.length;
					for(int j=0 ; j < updateLength; j++)
						int updateCount = updateCountArr[j];
						System.out.println("updateCount : " + updateCount);
		}catch(Exception ex)
			this.closeDBResource(stmt, dbConn);

	public static void main(String[] args) {
		/* Below are db connection required data. */
		String ip = "localhost";
		int port = 3306;
		String dbName = "test";
		String userName = "root";
		String password = "";
		/* Create an instance. */
		JDBCStatementExample jdbcStatementExample = new JDBCStatementExample();
		jdbcStatementExample.testBatchUpdate(ip, port, dbName, userName, password);

Source Code:

  1. [download id=”2551″]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.