Using Batch instead of PreparedStatement

Inserting a large amount of data into a database is typically done by preparing an INSERT statement and executing that statement multiple times. This increases the number of JDBC calls and impacts the performance. To reduce the number of JDBC calls and improve the performance, you can send multiple queries to the database at a time by using the addBatch method of the PreparedStatement object.

Let's look at the following example:

PreparedStatement ps = conn.prepareStatement(
"INSERT INTO ACCOUNT VALUES (?, ?)");
for (n = 0; n < 100; n++) {
ps.setInt(accountNumber[n]);
ps.setString(accountName[n]);
ps.executeUpdate();
}

In the preceding example, PreparedStatement is used to execute an INSERT statement multiple times. For executing the preceding INSERT operation, 101 network round-trips are required: one to prepare the statement, and the remaining 100 to execute the INSERT SQL statement. So, inserting and updating a large amount of data actually increases network traffic and, due to that, impacts performance. 

Let's see how we can reduce the network traffic and improve performance with the use of Batch:

PreparedStatement ps = conn.prepareStatement(
"INSERT INTO ACCOUNT VALUES (?, ?)");
for (n = 0; n < 100; n++) {
ps.setInt(accountNumber[n]);
ps.setString(accountName[n]);
ps.addBatch();
}
ps.executeBatch();

In the previous example, I used the addBatch() method. It consolidates all 100 INSERT SQLs and executes the entire operation with only two network round-trips: one for preparing the statement and another for executing the batch of consolidated SQLs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset