简单测试Jdbc批量操作对比
总是使用框架等等,都是封装好的操作,好久没用JDBC直接操作了;
今天没事测试了一下Batch和直接操作差别有多大;
仅是简单对比而已罢了:
不说了看结果...
@Testpublic void testJDBCBatch() throws Exception{ final ApplicationContext ac= new ClassPathXmlApplicationContext("pdsu/zhang/jdbcAopDemo/applictionContext.xml");// CallBack CountTime.getTime(new Handle(){public void handler() throws Exception {Connection con=ac.getBean("datasource", DataSource.class).getConnection();con.setAutoCommit(false); // 不设置 false 1000运行耗时:703ms :672msPreparedStatement stmt = con.prepareStatement("INSERT INTO student VALUES (?, ?)");for(int i=1;i<100000;i++){ // 循环本身 运行耗时:94msstmt.setString(1, "zhangNo."+i);stmt.setString(2, "123");//stmt.executeUpdate();//100运行耗时:109ms 1000运行耗时:657ms : 672msstmt.addBatch(); //100运行耗时:32ms 1000运行耗时:250ms : 219ms }stmt.executeBatch(); con.commit();// 10000运行耗时:1203ms 100000运行耗时:9406mscon.close();}});}class CountTime {public static void getTime(Handle handle) throws Exception {long start =System.currentTimeMillis();handle.handler();long end =System.currentTimeMillis();System.out.println("运行耗时:"+(end-start)+"ms");}}interface Handle{public void handler() throws Exception;}@Testpublic void testJDBCBatch2() throws Exception{ final ApplicationContext ac= new ClassPathXmlApplicationContext("pdsu/zhang/jdbcAopDemo/applictionContext.xml");CountTime.getTime(new Handle(){public void handler() throws Exception {Connection con=ac.getBean("datasource", DataSource.class).getConnection();con.setAutoCommit(false); PreparedStatement stmt = con.prepareStatement("INSERT INTO student VALUES (?, ?)");for(int i=1;i<10000;i++){ stmt.setString(1, "zhangNo."+i);stmt.setString(2, "123");stmt.addBatch(); }stmt.executeBatch(); stmt.clearBatch();for(int i=1;i<10000;i++){ stmt = con.prepareStatement("update student set pwd=?");stmt.setString(1, i+"");stmt.addBatch(); // 运行耗时:2422ms}stmt.executeBatch();// 或者 executeUpdate()都行stmt = con.prepareStatement("update student set pwd=? where name='zhang' ");stmt.setString(1, "123");stmt.executeUpdate();con.commit(); con.close();/**操作 批量同统一提交 单个统一提交 单个直接提交*1000条 运行耗时:391ms/437ms 运行耗时:8375ms 运行耗时:14969ms* 10K 运行耗时:3171ms*/}});}