读书人

容易测试Jdbc批量操作对比

发布时间: 2012-11-06 14:07:00 作者: rapoo

简单测试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;}


下面是简单写了通用计时器;
可见10000条记录运行耗时:1203ms 100000条运行耗时:9406ms
明显看出耗时比例3:1还大,批量10万条时耗内存一两百M吧;但是和数据库的操作简单利索啊。
下面看一个更有意思的:
@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*/}});}

对比一下子吧,测试10K的时候我实在不愿意等了...

呵呵,没事闲侃吧 1 楼 421584397 昨天 Hibernate与Jdbc的效率测试
http://www.verydemo.com/demo_c146_i183.html
Spring JDBC LOB操作 -
http://www.verydemo.com/demo_c143_i499.html

读书人网 >其他数据库

热点推荐