Using the batch feature of PreparedStatement

Source: Internet
Author: User

When you update a large amount of data, prepare an INSERT statement multiple times, causing many times of network connectivity. To reduce the number of JDBC calls to improve performance, you can use PreparedStatement's Addbatch () method to send multiple queries to the database at once. For example, let's compare the following example.

Example 1: Multiple executions of prepared Statement

PreparedStatement PS = conn.preparestatement (
"INSERT into employees values (?,?,?)");

for (n = 0; n <; n++) {

Ps.setstring (Name[n]);
Ps.setlong (Id[n]);
Ps.setint (Salary[n]);
Ps.executeupdate ();
}

Example 2: Using Batch

PreparedStatement PS = conn.preparestatement (
"INSERT into employees values (?,?,?)");

for (n = 0; n <; n++) {

Ps.setstring (Name[n]);
Ps.setlong (Id[n]);
Ps.setint (Salary[n]);
Ps.addbatch ();
}
Ps.executebatch ();

In Example 1, PreparedStatement is used to execute the INSERT statement multiple times. Here, 100 insert operations were performed, with a total of 101 network round trips. Of these, 1 roundtrip is the pre-stored statement, and the other 100 round trips perform each iteration. In Example 2, when you use the Addbatch () method in 100 insert operations, only two network round trips are used. 1 round trips are pre-stored statement, and another is the Execute batch command. Although the batch command uses more CPU cycles for the database, performance is improved by reducing network round trips. Remember, the greatest improvement in JDBC performance is to reduce the network traffic between the JDBC driver and the database.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.