最近由于业务上的需求,一张旧表结构中的数据,需要提取出来,根据规则,导入一张新表结构中,开发同学写了一个工具,用于实现新旧结构的transformation,
实现逻辑简单,就是使用jdbc从A表读出数据,做了一些处理,再存入新表B中,发现读取旧表的操作,非常缓慢,无法满足要求。
读取数据的示例代码,
conn = getConnection();
long start = System.currentTimeMillis();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
long mid_end = System.currentTimeMillis();
while (rs.next()) {
list.add(rs.getString(1));
}
long end = System.currentTimeMillis();
rs.close();
System.out.println("Interval1=" + (mid_end - start));
System.out.println("Interval2=" + (end - mid_end));
SQL语句读取10000条记录,其中,
Interval1=160ms
Interval2=29252ms
执行executeQuery()这个SQL检索的时间为160毫秒。
执行10000次rs.next以及rs.getString(1)的用时约为30秒,平均1条记录3毫秒。
如何才能提高读取的效率?
上面读取10000条记录,每一次rs.next时间只有3毫秒,但是由于需要10000次,所以才需要30秒,我们可以猜测,是否有可能每一次rs.next的执行,均需要和数据库交互,因为如果仅是字符串操作,不应该是这个数量级。
看一下官方文档的描述,《Database JDBC Developer's Guide》有一节介绍了Fetch Size,
By default, when Oracle JDBC runs a query, it retrieves a result set of 10 rows at a time from the database cursor. This is the default Oracle row fetch size value. You can change the number