使用JDBC進行批處理

來源:互聯網
上載者:User

使用JDBC進行批處理

當需要向資料庫發送一批SQL語句執行時,應避免向資料庫一條條的發送執行,而應採用JDBC的批處理機制,以提升執行效率。

實現批處理的兩種方式:

1) Statement.addBatch(sql) list

執行批處理SQL語句

a)         executeBatch()方法:執行批處理命令

b)        clearBatch()方法:清除批處理命令

public void testBatch(){

       Connection con=null;

       Statement st=null;

       ResultSet rs=null;

       //擷取串連

       try {

           con=DBManager.getConnection();

           String sql1="insert into testbatch values (1,'aaa')";

           String sql2="insert into testbatch values (2,'bbb')";

           String sql3="delete from testbatch where id=1";

           st=(Statement) con.createStatement();//在語句對象st中,應有一個集合對象list

           //向批中添加sql語句

           st.addBatch(sql1);

           st.addBatch(sql2);

           st.addBatch(sql3);

          

           //向mysql提交批

           st.executeBatch();//返回的是整形數組,sql語句對多少條資料產生影響就返回幾,所有返回3個值

           st.clearBatch();

       } catch (SQLException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

       //資源釋放

       finally{

           DBManager.release(con, st, rs);

       }

       }

l       採用Statement.addBatch(sql)方式實現批處理:

•         優點:可以向資料庫發送多條不同的SQL語句。

•         缺點:

•         SQL語句沒有先行編譯。

•         當向資料庫發送多條語句相同,但僅參數不同的SQL語句時,需重複寫上很多條SQL語句。

 

2) PreparedStatement.addBatch()

public void testBatch2(){

       Connection con=null;

       PreparedStatement st=null;

       ResultSet rs=null;

       //擷取串連

       try {

           con=DBManager.getConnection();

           String sql="insert into testbatch values (?,?)";

           st=con.prepareStatement(sql);//提供了先行編譯的sql語句

          

//一條一條的向批中添加

           /*st.setInt(1,3);

           st.setString(2, "dddd");//已經形成了一條完整的sql語句insert into
testbatch values (3,"dddd");

           st.addBatch();

          

           st.setInt(1, 4);

           st.setString(2, "qqqqq");//已經形成了第二條完整的sql語句insert into
testbatch values (4,"qqqqq");

           st.addBatch();*/

//通過迴圈方式向批中添加

           for(int i=0;i<1999;i++){

              st.setInt(1,i);

              st.setString(2, "aa"+i);

              st.addBatch();

              if(i%100==0){

                  st.executeBatch();//如果批中已經有100條語句了,就向mysql提交一次

                  st.clearBatch();

              }

           }

       } catch (SQLException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

      

       //資源釋放

       finally{

           DBManager.release(con, st, rs);

       }

    }

l     採用PreparedStatement.addBatch()實現批處理

•       優點:發送的是先行編譯後的SQL語句,執行效率高。

•       缺點:只能應用在SQL語句相同,但參數不同的批處理中。因此此種形式的批處理經常用於在同一個表中批量插入資料,或批次更新表的資料。

附加:DBManager.java對資料庫的連結

public class DBManager {

   

    private static String username;

    private static String password;

    private static String url;

    private static String driver;

 

    static{

       try{

           InputStream in = DBManager.class.getClassLoader().getResourceAsStream("config/dbcp.properties");

           Properties prop = new Properties();

           prop.load(in);

           driver = prop.getProperty("driverClassName");

           url = prop.getProperty("url");

           username = prop.getProperty("username");

           password = prop.getProperty("password");

           Class.forName(driver);

       }catch (Exception e) {

           throw new ExceptionInInitializerError(e);

       }

    }

    public static Connection getConnection()
throws
SQLException{

       return DriverManager.getConnection(url,
username, password);

    }

    public static void release(Connection conn,Statement st,ResultSet rs){

       if(rs!=null){

           try{

              rs.close();

           }catch (Exception e) {e.printStackTrace();}

            rs = null;

       }

       if(st!=null){

           try{

              st.close();

           }catch (Exception e) {e.printStackTrace();}

           st = null;

       }

       if(conn!=null){

           try{

              conn.close();

           }catch (Exception e) {e.printStackTrace();}

           conn = null;

       }

    }

}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.