必须关闭自动提交,否则频繁提交事务会影响速度

// 使用预处理语句+批处理
String baseSQL = "INSERT INTO my_table (col1, col2) VALUES (?, ?)";
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
     PreparedStatement pstmt = conn.prepareStatement(baseSQL)) {
    
    conn.setAutoCommit(false); // 关闭自动提交
    
    // 添加批处理参数
    for (int i = 0; i < 10000; i++) {
        pstmt.setInt(1, i);
        pstmt.setString(2, "value_" + i);
        pstmt.addBatch();
        
        if (i % 1000 == 0) { // 每1000条执行一次
            pstmt.executeBatch();
        }
    }
    
    pstmt.executeBatch(); // 执行剩余批处理
    conn.commit(); // 提交事务
    
} catch (SQLException e) {
    e.printStackTrace();
}
最后修改:2025 年 05 月 09 日
如果觉得我的文章对你有用,请随意赞赏