用JDBC向数据库中插入大量数据时的优化
2014-03-13 16:42
435 查看
使用jdbc向数据库插入100000条记录,分别使用statement,PreparedStatement,及PreparedStatement+批处理3种方式进行测试:
//1.使用statement插入100000条记录
//2.使用PreparedStatement对象
//3.使用PreparedStatement + 批处理
在Oracle 10g中测试,结果:
1.使用statement 耗时142秒;
2.使用PreparedStatement 耗时56秒;
3.使用PreparedStatement + 批处理耗时:
a.50条插入一次,耗时5秒;
b.100条插入一次,耗时2秒;
c.1000条以上插入一次,耗时1秒;
通过以上可以得出结论,在使用jdbc大批量插入数据时,明显使用第三种方式(PreparedStatement + 批处理)性能更优。
//1.使用statement插入100000条记录
public void exec(Connection conn){ try { //开始时间 Long beginTime = System.currentTimeMillis(); //设置手动提交 conn.setAutoCommit(false); Statement st = conn.createStatement(); for(int i=0;i<100000;i++){ String sql="insert into t1(id) values ("+i+")"; st.executeUpdate(sql); } //结束时间 Long endTime = System.currentTimeMillis(); System.out.println("st:"+(endTime-beginTime)/1000+"秒");//计算时间 st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
//2.使用PreparedStatement对象
public void exec2(Connection conn){ try { Long beginTime = System.currentTimeMillis(); conn.setAutoCommit(false);//手动提交 PreparedStatement pst = conn.prepareStatement("insert into t1(id) values (?)"); for(int i=0;i<100000;i++){ pst.setInt(1, i); pst.execute(); } conn.commit(); Long endTime = System.currentTimeMillis(); System.out.println("pst:"+(endTime-beginTime)/1000+"秒");//计算时间 pst.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
//3.使用PreparedStatement + 批处理
public void exec3(Connection conn){ try { conn.setAutoCommit(false); Long beginTime = System.currentTimeMillis(); //构造预处理statement PreparedStatement pst = conn.prepareStatement("insert into t1(id) values (?)"); //1万次循环 for(int i=1;i<=100000;i++){ pst.setInt(1, i); pst.addBatch(); //每1000次提交一次 if(i%1000==0){//可以设置不同的大小;如50,100,500,1000等等 pst.executeBatch(); conn.commit(); pst.clearBatch(); } } Long endTime = System.currentTimeMillis(); System.out.println("pst+batch:"+(endTime-beginTime)/1000+"秒"); pst.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
在Oracle 10g中测试,结果:
1.使用statement 耗时142秒;
2.使用PreparedStatement 耗时56秒;
3.使用PreparedStatement + 批处理耗时:
a.50条插入一次,耗时5秒;
b.100条插入一次,耗时2秒;
c.1000条以上插入一次,耗时1秒;
通过以上可以得出结论,在使用jdbc大批量插入数据时,明显使用第三种方式(PreparedStatement + 批处理)性能更优。
相关文章推荐
- 【Java/JDBC.ORM】 jdbc插入大量数据时优化处理
- 用Java向数据库中插入大量数据时的优化
- jdbc插入大量数据时优化处理(转)
- 【Java/JDBC.ORM】 jdbc插入大量数据时优化处理
- java jdbc向数据库插入大量数据
- 用Java向数据库中插入大量数据时的优化
- jdbc插入大量数据时优化处理-最近遇到的解决我一大难题
- Java向数据库中插入大量数据时的优化
- 关于数据库循环插入大量对象数据的解决办法
- JAVA中使用JDBC插入大量mysql中的数据
- Storm JDBC插入数据到数据库
- sqlite大量数据插入的优化
- Mysql大量插入数据时SQL语句的优化
- JAVA中使用JDBC插入大量mysql中的数据
- 当用JDBC向数据库中插入数据的中文问题
- 大量数据情况下单线程插入和多线程(高并发)insert数据库的性能测试
- 数据库优化及提高大量数据的查询效率
- Java:jdbc连接数据库插入中文数据乱码问题
- Mysql大量插入数据时SQL语句的优化
- JAVA中使用JDBC插入大量mysql中的数据