JDBC批量處理

來源:互聯網
上載者:User

Statement的execute()等方法一次只能執行一條SQL語句,如果同時有多條SQL語句要執行的話,可以使用addBatch()方法將要只系那個的SQL語句加入進來,然後執行executeBatch()方法,這樣就在一次方法調用中執行了多條SQL語句,以提高執行效率。

為了保證這一批語句全部成功或者失敗,應該把批處理放置在事務中進行:

try{

       conn.setAutoCommite(false);//把自動認可事務設定為false

       Statement  stmt=conn.createStatement();

       stmt.addBatch(“…”);//添加SQL語句

       stmt.addBatch(“…”);//添加SQL語句

       .  .  .

       Stmt.executeBatch();//執行批處理

       conn.commit();//提交事務

}catch(SQLException e){

       try{

              conn.rollback();//復原事務

}catch(SQLExceptione1){

       e 1.printStackTrace();

}

e.printStackTrace();

}finally{

       Try{

              Conn.setAutoCommit(true);//把自動認可事務設定為true

}catch(SQLExceptione){

       e.printStackTrace();

}

//關閉資源

.  .  .

}

使用PreparedStatement也可以進行批處理:

try{

       //啟動事務------把自動認可事務設定為false

       conn.setAutoCommit(false);

       pstmt=conn.preparedStatement(sql);

       pstmt.setXXX(1,…);//給預留位置賦值

       .  .  .

       //把這些操作添加到批處理中

       pstmt.addBatch();

 

       pstmt.setXXX(1,…);//給預留位置賦值

       .  .  .

       //把這些操作添加到批處理中

       Pstmt.addBatch();

 

       Pstmt.executeBatch();//執行批處理

       //提交事務

       Conn.commit();

}catch(SQLException e){

       //復原事務-------把所有的操作都取消

       try{

              conn.rollback();

}catch(SQLExceptione1){

       e 1.printStackTrace();

}

e.printStackTrace();

}finally{

       //關閉事務-----把自動認可事務設定為true

       try{

              conn.setAutCommit(true);

}catch(SQLExceptione){

       e.printStrackTrace();

}

//關閉資源

.   .   .

}

批處理中執行的語句只能是更新語句(insert、delete、update),否則會拋出異常。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.