JDBC入門(4)--- 批處理,jdbc入門

來源:互聯網
上載者:User

JDBC入門(4)--- 批處理,jdbc入門

1、Statement批處理

  當你有10條SQL語句要執行時,一次向伺服器發送一條SQL語句,這樣做的效率上極差,處理的方案是使用批處理,即一次向服務發送多條SQL語句,然後由伺服器一次性處理。

  批處理只針對更新(增刪改)語句,批處理與查詢無關。

  可以多次調用Statement類的addBatch(String sql)方法,把需要執行的所有SQL語句添加到一個“批”中,然後調用Statement類的excuteBatch()方法來執行當前“批中的語句”。

  • void addBatch(String sql):添加一條語句到“批”中。
  • int[] excuteBatch():執行“批”中所有的語句,傳回值表示每條語句所影響的行資料;
  • void clearBatch():清空“批”中的所有語句

2、PreparedStatement批處理

  PreparedStatement的批處理有所不同,因為每個PreparedStatement對象都綁定一條SQL模板。所以向PreparedStatement中添加的不是SQL語句,而是給“?”賦值。

 1 public class Demo5 { 2     /* 3     * pstmt對象內部有集合 4     * 1、用迴圈瘋狂向pstmt中添加sql參數,它自己有模板, 5     * 使用一組參數與模板就可以匹配一條sql語句 6     * 2、調用它的執行批方法,完成向資料庫發送。 7     * */ 8     @Test 9     public void fun1() throws Exception {10         /*11         * pstmt12         * */13         Connection con = JdbcUtils.getConnection();14         String sql = "INSERT INTO t_user VALUES (?,?)";15         PreparedStatement pstmt = con.prepareStatement(sql);16         for (int i = 0; i < 10000; i++) {17             pstmt.setInt(1,i+1);18             pstmt.setInt(2,i);19             pstmt.addBatch();//添加批,這一組參數就儲存到集合中;20         }21         long start = System.currentTimeMillis();22         pstmt.executeBatch();//執行批處理;23         long end = System.currentTimeMillis();24         System.out.println(end-start);25     }26 }

開啟批處理

MySQL的批處理也需要通過參數來開啟:rewriteBatchedStatements=true,如

url = jdbc:mysql://localhost:3306/mydb1?rewriteBatchedStatements=true

效果:

  • 批處理開啟前耗時:140794ms
  • 批處理開啟後耗時:174ms

聯繫我們

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