简单测试Jdbc批量操作对比

[i]总是使用框架等等,都是封装好的操作,好久没用JDBC直接操作了;
今天没事测试了一下Batch和直接操作差别有多大;
仅是简单对比而已罢了:[/i]
不说了看结果...

@Test
public 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 :672ms
PreparedStatement stmt = con.prepareStatement("INSERT INTO student VALUES (?, ?)");
for(int i=1;i<100000;i++){ // 循环本身 运行耗时:94ms
stmt.setString(1, "zhangNo."+i);
stmt.setString(2, "123");
//stmt.executeUpdate();//100运行耗时:109ms 1000运行耗时:657ms : 672ms
stmt.addBatch(); //100运行耗时:32ms 1000运行耗时:250ms : 219ms
}
stmt.executeBatch(); con.commit();
// 10000运行耗时:1203ms 100000运行耗时:9406ms
con.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吧;但是和数据库的操作简单利索啊。
[i]下面看一个更有意思的:[/i]

@Test
public 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的时候我实在不愿意等了...

呵呵,没事闲侃吧
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值