JDBC batch Update
Oracle实现的批处理更新效果不错,至于每次批处理的记录数还需要根据每条记录的大小,服务器的负载情况等多种因素进行微调。
1 private static void batchInsertTest(OracleDataSource ds)throws SQLException{
2
3 final int NUM=1000000;
4 final int COL=200000;
5 final int ROW=NUM/COL;
6 /*GregorianCalendar c = new GregorianCalendar(2010,1,1);
7 Date[] atimes=new Date[NUM];
8 Random rand =new Random();
9 for(int i=0;i<NUM;i++){
10 c.set(Calendar.DAY_OF_YEAR, rand.nextInt(360)+1);
11 atimes[i]=new Date(c.getTimeInMillis());
12 }*/
13
14 String sqlInsert="insert into AccessInfo(id,name) values(?,?)";
15 OracleConnection conn=null;
16 try {
17 conn = (OracleConnection) ds.getConnection();
18 conn.setAutoCommit(false);
19 conn.setImplicitCachingEnabled(true);
20 conn.setStatementCacheSize(10);
21 long start = System.currentTimeMillis();
22 PreparedStatement pstmt = conn.prepareStatement(sqlInsert);
23 try {
24 for (int i = 0; i < ROW; i++) {
25 for (int j = 0; j < COL; j++) {
26 int k = i * COL + j;
27 pstmt.setInt(1, k);
28 pstmt.setString(2, "person" + k);
29 // pstmt.setDate(2, atimes[k]);
30 pstmt.addBatch();
31 }
32 pstmt.executeBatch();
33
34 }
35 System.out.printf("Elapsed time: %d ms",
36 (System.currentTimeMillis() - start));
37
38 } catch (Exception e) {
39 conn.rollback();
40 System.err.println("Insertion has been rolled back!");
41 throw new SQLException(e);
42 } finally {
43 if (pstmt != null)
44 pstmt.close();
45 }
46
47 conn.commit();
48
49 }finally{
50 if(conn!=null)
51 conn.close();
52 }
53 }
上面代码只使用了两个短字段来测试性能,实验数据表明:每1万条记录插入时间可达到20ms。