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