JDBC批处理

迈不过友情╰ 2022-04-02 12:22 329阅读 0赞

JDBC实现批处理有两种方式:statementpreparedstatement
先比较一下两种方式的批处理:
1.采用Statement.addBatch(sql)方式实现批处理的优缺点
采用Statement.addBatch(sql)方式实现批处理:
优点:可以向数据库发送多条不同的SQL语句。
缺点:SQL语句没有预编译。
当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。
2.采用PreparedStatement.addBatch()方式实现批处理的优缺点
采用PreparedStatement.addBatch()实现批处理
优点:发送的是预编译后的SQL语句,执行效率高。
缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。

下面具体介绍一下:

一.使用Statement完成批处理

1.使用Statement对象添加要批量执行SQL语句,如下:

  1. Statement.addBatch(sql1);
  2. Statement.addBatch(sql2);
  3. Statement.addBatch(sql3);

2、执行批处理SQL语句:Statement.executeBatch();
3、清除批处理命令:Statement.clearBatch();

1.1 使用Statement完成批处理范例

  1. public void testJdbcBatchHandleByStatement(){
  2. Connection conn = null;
  3. Statement st = null;
  4. ResultSet rs = null;
  5. try{
  6. conn = JdbcUtils.getConnection();
  7. st = conn.createStatement();
  8. //添加要批量执行的SQL
  9. st.addBatch(sql1);
  10. st.addBatch(sql2);
  11. st.addBatch(sql3);
  12. st.addBatch(sql4);
  13. st.addBatch(sql5);
  14. st.addBatch(sql6);
  15. st.addBatch(sql7);
  16. //执行批处理SQL语句
  17. st.executeBatch();
  18. }catch (Exception e) {
  19. conn.rollback();
  20. e.printStackTrace();
  21. }finally{
  22. //清除批处理命令
  23. st.clearBatch();
  24. JdbcUtils.release(conn, st, rs);
  25. }
  26. }

二、使用PreparedStatement完成批处理

1.PerparedStatement在conn.prepareStatement(sql); 的时候需要将sql直接传入。
2.添加批处理: pst.addBatch();

2.1 使用PreparedStatement完成批处理范例

  1. public void testJdbcBatchHandleByPrepareStatement(){
  2. long starttime = System.currentTimeMillis();
  3. Connection conn = null;
  4. PreparedStatement pst = null;
  5. ResultSet rs = null;
  6. try{
  7. conn = JdbcUtils.getConnection();
  8. String sql = "insert into testbatch(id,name) values(?,?)";
  9. pst = conn.prepareStatement(sql);
  10. for(int i=1;i<1000008;i++){ //i=1000 2000
  11. pst.setInt(1, i);
  12. pst.setString(2, "aa" + i);
  13. pst.addBatch();
  14. if(i%1000==0){
  15. pst.executeBatch();
  16. pst.clearBatch();
  17. }
  18. }
  19. pst.executeBatch();
  20. }catch (Exception e) {
  21. e.printStackTrace();
  22. }finally{
  23. JdbcUtils.release(conn, pst, rs);
  24. }

参考文章

发表评论

表情:
评论列表 (有 0 条评论,329人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JDBC处理

    当存在大量的数据需要操作时,如果使用通常的做法会十分浪费时间,因为一次数据库操作的时间主要在建立连接和释放资源上(即使应用了连接池,这两个步骤依然十分耗费时间)。 因此,当有

    相关 jdbc处理

    当需要向数据库发送一批sql指令时,应该避免一条一条的向数据库发送命令,而应该采用jdbc的批处理机制,以提升效率。 jdbc提供两种批处理机制: 第一种: statem

    相关 jdbc处理

    当需要向数据库发送一批sql指令时,应该避免一条一条的向数据库发送命令,而应该采用jdbc的批处理机制,以提升效率。 jdbc提供两种批处理机制: 第一种: statem

    相关 使用JDBC进行处理

    适用场景: 当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应该采用JDBC的批处理机制,以提升执行效率。 实现方式: 方式一:Stat