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.