Java批处理操作

来源:互联网 发布:微小宝类似软件 编辑:程序博客网 时间:2024/06/03 21:51

  批处理,可以大幅度提升大量增、删、改的速度,就是对大数据操作有很大的效率提升。

  与上篇文章中提到的“连接池”相似。其实就是先将多次操作(增删改)打包,然后再一次发送执行

  主要用到两个方法:

   Ø  打包:PreparedStatement.addBatch();

   Ø  发送、执行:PreparedStatement.executeBatch();

 

  下面看做同一件事,用批处理和不用批处理的效率对比,源码如下:

import java.sql.Connection;import java.sql.Date;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * @author-zhipeng * * 对比批处理与非批处理的差别(本例的循环所在位置) */public class BatchTest {/** * 对比“批处理”与“非批处理”的执行效率 */public static void main(String[] args) throws SQLException {//非批处理,插入100条数据所花费的时间long start = System.currentTimeMillis();for (int i = 0; i < 100; i++)create(i);long end = System.currentTimeMillis();System.out.println("create:" + (end - start));//批处理,插入100条数据所花费的时间start = System.currentTimeMillis();createBatch();end = System.currentTimeMillis();System.out.println("createBatch:" + (end - start));}/** * 非批处理-插入1条数据 */static void create(int i) throws SQLException {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {//JdbcUtils为自定义的操作类,这里不多介绍conn = JdbcUtils.getConnection();String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);ps.setString(1, "no batch name" + i);ps.setDate(2, new Date(System.currentTimeMillis()));ps.setFloat(3, 100f + i);//执行插入ps.executeUpdate();} finally {//释放资源JdbcUtils.free(rs, ps, conn);}}/** * 批处理-插入100条数据 */static void createBatch() throws SQLException {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = JdbcUtils.getConnection();String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";ps = conn.prepareStatement(sql);//注意批处理与“非批处理”循环放的位置for (int i = 0; i < 100; i++) {ps.setString(1, "batch name" + i);ps.setDate(2, new Date(System.currentTimeMillis()));ps.setFloat(3, 100f + i);//关键方法1:打包ps.addBatch();}//关键方法2:执行int[] is = ps.executeBatch();} finally {JdbcUtils.free(rs, ps, conn);}}}

 

  运行效果:

 

 

  这是执行100条数据的差距,可以想象对大数据的效率提升改有多大。

 

0 0
原创粉丝点击