zoukankan      html  css  js  c++  java
  • JDBC批处理

    当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。

    1、第一种方式

    
    
     1 package com.demo;
     2 
     3 import java.sql.Connection;
     4 import java.sql.PreparedStatement;
     5 import java.sql.ResultSet;
     6 import java.sql.SQLException;
     7 import java.sql.Statement;
     8 
     9 import org.junit.Test;
    10 
    11 import com.utils.DButils;
    12 
    13 //jdbc批处理
    14 public class Demo3 {
    15     //批处理第一种方式
    16     @Test
    17     public void test1() throws SQLException{
    18         Connection con = null;
    19         Statement st = null;
    20         ResultSet result = null;
    21         
    22         try{
    23             con = DButils.getConnection();
    24             String sql1 = "insert into testbatch(id,name) values('1','aaaa')";
    25             String sql2 = "update testbatch set name='bbbb' where id=1";
    26             st = con.createStatement();
    27             st.addBatch(sql1);//Statement维护了一个list集合
    28             st.addBatch(sql2);
    29             
    30             //返回一个int[1,1]数组代表每条sql语句影响几行数组
    31             st.executeBatch();
    32             st.clearBatch();
    33             
    34         }finally{
    35             DButils.release(con, st, result);
    36         }
    37     }
    
    
    
     

     

    2、第二种方式

     1 //实现批处理的第二种方式  适用于批量更新和插入
     2     @Test
     3     public void test2() throws SQLException{
     4         Connection con = null;
     5         PreparedStatement st = null;
     6         ResultSet result = null;
     7         long startTime = System.currentTimeMillis();
     8         try{
     9             con = DButils.getConnection();
    10             String sql = "insert into testbatch(id,name) values(?,?)";
    11             st = con.prepareStatement(sql);
    12             for(int i=1;i<10000;i++){
    13                 st.setString(1,i+"");
    14                 st.setString(2,"aa"+i);
    15                 st.addBatch();
    16             }
    17             st.executeBatch();
    18             st.clearBatch();    
    19             
    20         }finally{
    21             DButils.release(con, st, result);
    22         }
    23         long endTime = System.currentTimeMillis();
    24         System.out.println("花费时间:"+(endTime-startTime)/1000+"秒");
    25     }
    26 }
  • 相关阅读:
    Access操作必须使用一个可更新的查询
    SAP资料学习好地方
    Access关键词大全
    WPF零散笔记
    WPF:如何实现单实例的应用程序(Single Instance)
    WPF应用程序启动显示图片资源
    Drawable、Bitmap、Canvas和Paint的关系以及部分使用方法
    C#中一种可调用的异常处理方法
    easyui datagrid 点击列表头排序出现错乱的原因
    easyui datagrid 没数据时显示滚动条的解决方法
  • 原文地址:https://www.cnblogs.com/niuchuangfeng/p/9174467.html
Copyright © 2011-2022 走看看