Java -- JDBC 批处理

来源:互联网 发布:java split有空字符串 编辑:程序博客网 时间:2024/05/17 02:17

两种批处理方式:

采用Statement.addBatch(sql)方式实现批处理:
优点:可以向数据库发送多条不同的SQL语句。
缺点:
•SQL语句没有预编译。
•当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。例如:

  Insert into user(name,password) values(‘aa’,’111’);

  Insertinto user(name,password) values(‘bb’,’222’);

  Insertinto user(name,password) values(‘cc’,’333’);

  Insertinto user(name,password) values(‘dd’,’444’);

采用PreparedStatement.addBatch()实现批处理
优点:发送的是预编译后的SQL语句,执行效率高。
缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。
public class Demo3 { /* create table testBatch ( id int primary key, name varchar(20) ); */@Testpublic void testBatch1()  //方式一:同时处理多类多条SQL语句,但效率较低(没有预编译){Connection conn = null;Statement st = null;ResultSet rs = null;try{conn = JdbcUtils.getConnection();String sql1 = "insert into testBatch(id,name) values(1,'kevin')";String sql2 = "insert into testBatch(id,name) values(2,'xiang')";String sql3 = "delete from testBatch where id=1";st = conn.createStatement();st.addBatch(sql1);st.addBatch(sql2);st.addBatch(sql3);st.executeBatch();st.clearBatch();}catch (Exception e){e.printStackTrace();}finally {JdbcUtils.release(conn, st, rs);}}@Testpublic void testBatch2()  //方式二:效率高,用于SQL相同 只是参数不同的批处理{long  startTime = System.currentTimeMillis();Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try{conn = JdbcUtils.getConnection();String sql = "insert into testBatch(id,name) values(?,?)";st = conn.prepareStatement(sql);for(int i=1; i<10000; i++){st.setInt(1, i);st.setString(2, "kevin" + i);st.addBatch();if(i%1000==0){st.executeBatch();st.clearBatch();System.out.println(i);}}st.executeBatch();st.clearBatch();}catch (Exception e){e.printStackTrace();}finally {JdbcUtils.release(conn, st, rs);}long  endTime = System.currentTimeMillis();System.out.println("总共用时: " + (endTime-startTime)/1000 + "秒");}}


0 0
原创粉丝点击