JDBC批量插入优化方案

995 阅读1分钟
  • 使用prepareStatement预加载
  • 使用addbatch() + executeBatch() + clearBatch()
  • 关闭事务自动提交,实现手动提交 Connection 的 setAutoCommit(false) / commit()
/*
* 1. 使用prepareStatement预加载
* 2. 使用addbatch()方法
* 3. 使用Connection 的 setAutoCommit(false)  /  commit()
*/
@Test
public void testInsert2() throws Exception{
	long start = System.currentTimeMillis();
		
	Connection conn = JDBCUtils.getConnection();
		
	//1.设置为不自动提交数据
	conn.setAutoCommit(false);
		
	String sql = "insert into goods(name)values(?)";
	PreparedStatement ps = conn.prepareStatement(sql);
		
	for(int i = 1;i <= 1000000;i++){
		ps.setString(1, "name_" + i);
			
		//1.“攒”sql
		ps.addBatch();
			
		if(i % 500 == 0){
			//2.执行
			ps.executeBatch();
			//3.清空
			ps.clearBatch();
		}
	}
		
	//2.提交数据
	conn.commit();
		
	long end = System.currentTimeMillis();
	System.out.println("花费的时间为:" + (end - start));//1000000条:4978 
		
	JDBCUtils.closeResource(conn, ps);
}