JDBC(六)批处理

批处理的 三个关键步骤:

1. 在数据库的url后添加参数: rewriteBatchedStatements=true
jdbc:mysql://localhost:3306/myself?rewriteBatchedStatements=true
2. 使用 .addBatch()方法将操作添加到批处理中
3. 使用.executeBatch()方法 执行批处理操作

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

public class JdbcBatchExample {

    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/your_database";
    private static final String USER = "your_username";
    private static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 1. 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立数据库连接
            connection = DriverManager.getConnection(URL, USER, PASSWORD);

            // 3. 创建 PreparedStatement 对象
            String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
            preparedStatement = connection.prepareStatement(sql);

            // 4. 添加批处理操作
            preparedStatement.setString(1, "Alice");
            preparedStatement.setString(2, "alice@example.com");
            preparedStatement.addBatch();

            preparedStatement.setString(1, "Bob");
            preparedStatement.setString(2, "bob@example.com");
            preparedStatement.addBatch();

            preparedStatement.setString(1, "Charlie");
            preparedStatement.setString(2, "charlie@example.com");
            preparedStatement.addBatch();

            // 5. 执行批处理操作
            int[] updateCounts = preparedStatement.executeBatch();

            // 6. 输出结果
            System.out.println("Batch update completed. Number of rows affected: " + updateCounts.length);

        } catch (ClassNotFoundException e) {
            System.err.println("Database driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("SQL error occurred.");
            e.printStackTrace();
        } finally {
            // 7. 关闭资源
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容