我试图从java应用程序向数据库中的各种表中插入大量的行。所以基本上我有一个单一的连接,我创建了多个Prepare语句。然后我通过设置准备语句的变量来准备几个插入。最后,我执行每个Prepare语句作为执行批处理并关闭语句。在Java Sql中执行批准的准备语句需要很长时间在最后一次迭代中
问题我面临的是,我正在对上述过程进行迭代。
我有一个方法writeToDataBase(),它执行上述操作,并且此方法在循环内部调用。因此批量插入会发生很多次(每批次包含20个物体)。每次这种插入需要大约5到6秒才能在一次迭代中进行批量插入。但是在最后一次迭代中需要40秒的很长时间。
我认为这可能是由于上一次迭代中写入的数据所致。因此,我也改变了数据,使其轻量化,但即使如此,问题仍然存在。然后我试着禁用自动提交并手动提交。这也没有帮助。
我也改变了迭代次数。例如,
在20个计数的循环中,第20个循环将花费大量时间。所以我改变它运行5次。但是这次第五回合运行时间更长。基本上最后一个循环需要很长时间来执行批处理。
检查是否有内存泄漏,我也关闭语句是它的执行。但我无法理解为什么会发生这种情况。
下面提供了代码片段。
for(ArrayList<DocumentObject> batch : documentBatches){
DBWriter.writeToDataBase(batch);
}
public static synchronized boolean writeToDataBase(ArrayList<DocumentObject> batch) {
try {
//Prepare Statements for insertion
String insertDocumentTableSQL = "INSERT INTO TEST.DOCUMENTS values (?,?,?,?,?,?,?,?);";
PreparedStatement documentPreparedStatement = connection.prepareStatement(insertDocumentTableSQL);
String insertSentencesTableSQL = "INSERT INTO TEST.SENTENCES values (?,?,?,?,?,?);";
PreparedStatement sentencesPreparedStatement = connection.prepareStatement(insertSentencesTableSQL);
//Preparing multiple inserts to the prepare statements
for(DocumentObject docObj : batch){
documentPreparedStatement = prepareInsertsToDocumentsTable(docObj,documentPreparedStatement); //sets the '?' in the query with actual values and adds it to the batch
sentencesPreparedStatement = prepareInsertsToSentencesTable(headlineSRLDocument, sectionId,sentencesPreparedStatement);
}
//execute the preparestatements
connection.setAutoCommit(false);
long start = System.currentTimeMillis();
documentPreparedStatement.executeBatch();
sentencesPreparedStatement.executeBatch();
connection.commit();
documentPreparedStatement.close();
sentencesPreparedStatement.close();
System.out.println("time taken for Execute Statements: "+(System.currentTimeMillis()-start)/1000+" seconds");
return true;
}
下面是控制台输出,我有跟踪每次迭代所需的时间。采取
时间执行语句:3秒
时间采取执行语句:4秒
时间采取执行语句:4秒
时间采取执行语句:4秒
执行时间:5秒
采取执行语句时间:5秒
时间采取执行语句:9秒
时间采取执行语句:10秒
时间采取执行语句:6秒
采取执行语句时间:47秒 < ------最后一次迭代花费更多的时间
尝试在每次调用中添加这些时序语句以确定哪些函数需要更多时间?顺便说一句,这是什么数据库? –
是目前发生的垃圾收集活动吗? –
嗨Sameer,我正在使用SAP HANA数据库。我发现.executeBatch()语句需要更多时间。但是在其他迭代中,它不会消耗太多时间。我不确定垃圾收集活动。 –