jdbc学习总结五之批处理

来源:互联网 发布:mac 手写 编辑:程序博客网 时间:2024/06/08 05:10

jdbc批处理有两种方式,一种是statement 可以将不同的sql一起发送,缺点是每个sql都需要写,另一种为preparedstatement 可以发送sql相同,参数不同的批量sql,适用于同一张表的批量插入。

create table test_batch(id int PRIMARY key,name VARCHAR(20))
<span style="white-space:pre"></span>@Testpublic void testStatementBatch() throws SQLException{Connection cn = JDBCUtils.getConnection();Statement st = cn.createStatement();String sql1 = "delete from test_batch where id = 1";String sql2 = "update test_batch  set id = 3,name = 'test3' where id = 2";/*String sql1 = "insert into test_batch values(1,'test1')";String sql2 = "insert into test_batch values(2,'test2')";*/st.addBatch(sql1);st.addBatch(sql2);st.executeBatch();st.clearBatch();st.close();cn.close();}
我们看一下preparedStatement 批量插入一张表

<span style="white-space:pre"></span>@Testpublic void testpreparedBatch() throws SQLException{long startTime = System.currentTimeMillis();Connection cn = JDBCUtils.getConnection();cn.setAutoCommit(false);String sql = "insert into test_batch values(?,?)";PreparedStatement ps = cn.prepareStatement(sql);for(int i = 1;i < 1000000;i++){ps.setInt(1, i);ps.setString(2, "test"+i);ps.addBatch();if(i%10000 == 0){ps.executeBatch();ps.clearBatch();cn.commit();}}ps.executeBatch();ps.close();cn.commit();cn.setAutoCommit(true);cn.close();long endTime = System.currentTimeMillis();System.out.println("程序花费时间"+(endTime - startTime)/1000+"秒");}
插入一百万数据,每一万次执行并清空一次,我们看一下结果

程序花费时间14秒

0 0
原创粉丝点击