亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

測試JDBC批處理效率沒變化

測試JDBC批處理效率沒變化

拉莫斯之舞 2019-02-24 09:07:20
我在學習 JDBC 批處理時, 為比較 Statement, PreparedStatement 和 JDBC Batch 操作之間的效率,寫一個例子:向數據庫中插入 100,000 條記錄,并記錄消耗的時間。然后分別用這三種方式實現,可每次測試的結果卻都是幾乎相同沒變化,請教大神這是為什么? import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; public class BatchTest { /** * 使用 Statement 進行批處理操作 */ @Test public void testBatchWithStatement(){ Connection connection = null; Statement statement; String sql; try { connection = JDBCUtils.getConnection(); JDBCUtils.beginTx(connection); statement = connection.createStatement(); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { sql = "INSERT INTO batch VALUES(" + i +")"; statement.executeUpdate(sql); } long end = System.currentTimeMillis(); System.out.println(end - start); JDBCUtils.commit(connection); } catch (Exception e) { e.printStackTrace(); JDBCUtils.rollback(connection); } } /** * 使用 PreparedStatement 進行批處理操作 */ @Test public void testBatchWithPreparedStatement(){ Connection connection = null; PreparedStatement statement; String sql; try { connection = JDBCUtils.getConnection(); JDBCUtils.beginTx(connection); sql = "INSERT INTO batch VALUES(?)"; statement = connection.prepareStatement(sql); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { statement.setInt(1, i + 1); statement.executeUpdate(); } long end = System.currentTimeMillis(); System.out.println(end - start); JDBCUtils.commit(connection); } catch (Exception e) { e.printStackTrace(); JDBCUtils.rollback(connection); } } /** * 使用 Batch 進行批處理操作 */ @Test public void testBatch(){ Connection connection = null; PreparedStatement statement; String sql; try { connection = JDBCUtils.getConnection(); JDBCUtils.beginTx(connection); sql = "INSERT INTO batch VALUES(?)"; statement = connection.prepareStatement(sql); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { statement.setInt(1, i + 1); statement.addBatch(); if ((i + 1) % 500 == 0){ statement.executeBatch(); statement.clearBatch(); } } if (100000 % 300 != 0){ statement.executeBatch(); statement.clearBatch(); } long end = System.currentTimeMillis(); System.out.println(end - start); JDBCUtils.commit(connection); } catch (Exception e) { e.printStackTrace(); JDBCUtils.rollback(connection); } } }
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 507 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號