JDBC preparedStatement executeBatch 效率低

问题

目前在优化一份代码,通过日志定位,发现程序的主要的时间花费在excuteBatch语句上。

问题代码

PreparedStatement ps = tempbaseCon.prepareStatement(sql);
while (rs.next()) {
    //读取数据
    for (int i = 2; i <= columnCount; i++) {
        ps.setObject(i - 1, rs.getObject(i));
    }
    ps.addBatch();

}

ps.executeBatch();

问题分析

1 在测试环境下,通过这段代码插入440条数据,花费了15s左右的时间
2 在测试环境下,不采用executeBatch语句,直接用拼接好得insert into tableName values(…),(…)语句,最后插入耗时不足1s
3 executeBatch语句和excute语句的差别就是在于是否同时批量运行多条语句
4 在默认设置下,jdbc的Connection是采用默认提交的策略的,每运行一条语句就提交一次,这个提交会生成回滚日志等数据,所以比较耗时
5 我们需要将Connection的提交策略改成手动提交

解决方案

 tempbaseCon.setAutoCommit(false);
 ps.executeBatch();
 tempbaseCon.commit();
 tempbaseCon.setAutoCommit(true);

refer

http://www.iteye.com/problems/67049

猜你喜欢

转载自blog.csdn.net/u010953266/article/details/80068348