Use the batch function of preparedstatement

Source: Internet
Author: User

When updating a large amount of data, prepare an insert statement is executed multiple times, which may lead to many network connections. to reduce the number of JDBC calls and improve performance, you can use the addbatch () method of preparedstatement to send multiple queries to the database at a time. for example, let's compare the following example.

Example 1: Execute prepared statement multiple times

Preparedstatement PS = conn. preparestatement (
"Insert into employees values (?, ?, ?) ");

For (n = 0; n <100; n ++ ){

PS. setstring (name [N]);
PS. setlong (ID [N]);
PS. setint (salary [N]);
Ps.exe cuteupdate ();
}

Example 2: Use batch

Preparedstatement PS = conn. preparestatement (
"Insert into employees values (?, ?, ?) ");

For (n = 0; n <100; n ++ ){

PS. setstring (name [N]);
PS. setlong (ID [N]);
PS. setint (salary [N]);
PS. addbatch ();
}
Ps.exe cutebatch ();

In example 1, preparedstatement is used to execute the insert statement multiple times. here, 100 insert operations are performed, with a total of 101 network round-trips. one round trip is the pre-storage statement, and the other 100 round trips are executed for each iteration. in Example 2, when the addbatch () method is used in 100 insert operations, only two network round trips are performed. one round trip is the pre-storage statement, and the other is the execution of the batch command. although batch commands use more CPU cycles for databases, performance is improved by reducing network round-trips. remember, the biggest improvement of JDBC performance is to reduce network communication between JDBC drivers and databases.
 

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.