package cc.smtweb.biz.mztb.web.task;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcBatchInsertExample {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";
        Connection connection = DriverManager.getConnection(url, username, password);
        try {
            connection.setAutoCommit(false); // 关闭自动提交，开启事务

            String sql = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                for (int i = 1; i <= 1000; i++) {
                    statement.setString(1, "Value " + i);
                    statement.setInt(2, i);
                    statement.addBatch(); // 添加到批处理中
                }
                statement.executeBatch(); // 执行批处理
            }
            connection.commit(); // 提交事务
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                // 如果出现异常，回滚事务
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}