Updated on 2025-09-04 GMT+08:00

Complete Example

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.sql.DriverManager;
public class TestBatch {
    public static Connection getConnection() throws ClassNotFoundException, SQLException{
 String driver = "com.huawei.gaussdb.jdbc.Driver";
        // Specify the source URL of the database. (Adjust $ip, $port, and database based on the actual services.)
        String sourceURL = "jdbc:gaussdb://$ip:$port/database";
        // Obtain the username and password from the environment variables.
        String userName = System.getenv("EXAMPLE_USERNAME_ENV");
        String password = System.getenv("EXAMPLE_PASSWORD_ENV");
        Class.forName(driver);
        return DriverManager.getConnection(sourceURL, userName, password);
    }
    public static void main(String[] args) {
 String sql = "insert into test_batch(v1,v2) values(?,?)";
        try (Connection conn = getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            conn.setAutoCommit(false);
            for (int i = 0; i < 5; i++) {
                preparedStatement.setInt(1, 1);
                preparedStatement.setString(2, "value2_" + i);
                preparedStatement.addBatch();
            }
            int[] results = preparedStatement.executeBatch();
            conn.commit();
            System.out.println(Arrays.toString(results));
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Result Verification

The preceding execution result shows the number of data records affected by the batch operation.

When you use preparedStatement for batch insertion, it returns an array of INT results, with results[0] indicating the total number of data records affected by the batch operation.

[5, 0, 0, 0, 0]

Rollback Method

To roll back operations within a specific transaction, call the Rollback API of the transaction object.