A batch statement can be used to execute multiple update commands as single unit in a database manipulation. This statement in the database is not executed one by one but as a single execution instead. In some cases, using a batch update can be more efficient than to execute the commands separately.
In this example, you are shown how to create a batch command to insert some products into a database table.
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
public class JDBCBatchExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
// Turn of the auto-commit mode
connection.setAutoCommit(false);
try (Statement statement = connection.createStatement()) {
// And some batch to insert some product information into
// the product table
statement.addBatch("INSERT INTO product (code, name) " +
"VALUE ('P0000006', 'Championship Manager')");
statement.addBatch("INSERT INTO product (code, name) " +
"VALUE ('P0000007', 'Transport Tycoon Deluxe')");
statement.addBatch("INSERT INTO product (code, name) " +
"VALUE ('P0000008', 'Roller Coaster Tycoon 3')");
statement.addBatch("INSERT INTO product (code, name) " +
"VALUE ('P0000009', 'Pro Evolution Soccer')");
// To execute a batch command, we must call the executeBatch()
// method.
int[] updateCounts = statement.executeBatch();
System.out.println("updateCounts = " + Arrays.toString(updateCounts));
// Commit our transaction
connection.commit();
} catch (SQLException e) {
connection.rollback();
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024