如何在db2中生成和插入大型数据集?

时间:2013-05-27 05:39:57

标签: database jdbc db2

我更改了代码,此代码插入30 000行/分钟,但速度太慢。我能不能再告诉我如何提高速度?

Connection connection = poolledConnection.getConnection(); 
connection.setAutoCommit(false); 
int bathcount = 0; 
Statement st = connection.createStatement(); 
    for (condit){ 
        st.addBatch(sql); 
            if (bathcount >= 10000){ 
                st.executeBatch(); 
                connection.commit(); 
                st.clearBatch();
                bathcount = 0; 
            }
        bathcount++; 
    } 
}

1 个答案:

答案 0 :(得分:0)

由于您使用的是Statement而不是PreparedStatement,因此DB2可能正在为每个insert语句做准备。准备一次,而不是数千次或数百万次,将为您节省大量的CPU时间。

为了提高速度,您应该有一个带有参数标记的SQL语句,并为每一行设置这些参数。

我假设在你的例子中,你必须以某种方式为每一行构建SQL。如果我错了,并且您为每一行使用相同的插入值,则可以跳过设置参数值,它会更快。

因此,对于我建议的更改,它看起来像这样(我假设这是Java):

String sql = "INSERT INTO TBL (COLS...) VALUES (?,?...)";

Connection connection = poolledConnection.getConnection(); 
connection.setAutoCommit(false); 
int bathcount = 0; 
PreparedStatement ps = connection.prepareStatement(sql); 
    for (MyObject object : objectList /*conduit???*/){
        ps.setString(1,object.getVal1());
        ps.setString(2,object.getVal2()); 
        ps.addBatch(); 
            if (bathcount >= 10000){ 
                ps.executeBatch(); 
                connection.commit(); 
                bathcount = 0; 
            }
        bathcount++; 
    } 
    /* Make sure you add this to get the last batch if it's not exactly 10k*/
    if (batchcount > 0) {
       ps.executeBatch(); 
       connection.commit(); 
    }
}