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. */
	dbConn.setAutoCommit(false);
			
	/* Get statement object. */
	Statement stmt = dbConn.createStatement();
		
    /* Add sql in batch, each sql can operate different table. */		
	stmt.addBatch(sql1);
	
	stmt.addBatch(sql2);
	
	stmt.addBatch(sql3);
	
	stmt.addBatch(sql4);
	
	stmt.addBatch(sql5);
	
	stmt.addBatch(sql6);

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

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.

READ :   JDBC Statement Examples - Insert, Delete, Update, Select Record

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]om' 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;
		try
		{
			/* 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();
			if(supportBatch)
			{
				System.out.println("This database support batch update.");
			}else
			{
				System.out.println("This database do not support batch update.");
			}
			
			
			/* Disable auto commit. */
			dbConn.setAutoCommit(false);
			
			/* Get statement object. */
			stmt = dbConn.createStatement();
			
			if(sqlArr!=null)
			{
				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();
					
				    dbConn.commit();
				    
				    dbConn.setAutoCommit(true);
					
					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)
		{
			ex.printStackTrace();
		}finally
		{
			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 “JDBCStatementBatchExample.zip” JDBCStatementBatchExample.zip – Downloaded 59 times – 2 KB

(Visited 1,271 times, 1 visits today)

Leave a Reply

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.