---
title: "jdbc 批量提交"
author: "Fred_Han"
date: "2012-09-28T19:11:06Z"
tags: []
categories: ["数据库"]
slug: "jdbc"
draft: false
lastmod: "2012-09-28T19:11:06Z"
id: 1688229
url: "https://fred-han.iteye.com/blog/1688229"
---

场景：大批量新增数据

对比：逐笔提交和批次提交

 

记录数：2322条记录

测试结果：单笔提交：22938毫秒；批量提交：172毫秒

 

批量提交相关代码：

            connection = dataSource.getConnection();  
            connection.setAutoCommit(false);  
            // 组装新增sql  
            String sql = assembleInsertSql();  
            statement = connection  
                    .prepareStatement(sql);  
            for (int i = 0; i &lt; beans.size(); i++) {  
                // 组装statement参数  
                aseembleStatement(statement, beans.get(i));  
                statement.addBatch();  
                // 每1000笔提交一次  
                if (i % 1000 == 0) {  
                    statement.executeBatch();  
                    connection.commit();  
                    statement.clearBatch();  
                }  
            }  
            statement.executeBatch();  
            connection.commit();