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 database.
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCBatchExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
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 products (code, name) " +
"VALUE ('P0000006', 'Championship Manager')");
statement.addBatch("INSERT INTO products (code, name) " +
"VALUE ('P0000007', 'Transport Tycoon Deluxe')");
statement.addBatch("INSERT INTO products (code, name) " +
"VALUE ('P0000008', 'Roller Coaster Tycoon 3')");
statement.addBatch("INSERT INTO products (code, name) " +
"VALUE ('P0000009', 'Pro Evolution Soccer')");
// To execute a batch command we must call the executeBatch()
// method.
int[] updateCounts = statement.executeBatch();
// 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.0.32</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023