【发布时间】:2010-05-12 09:31:46
【问题描述】:
考虑以下方法,从某些数据结构 (InteractionNetwork) 读取数据并使用 SQLite-JDBC dirver 将它们写入 SQLite 数据库中的表:
private void loadAnnotations(InteractionNetwork network) throws SQLException {
PreparedStatement insertAnnotationsQuery =
connection.prepareStatement(
"INSERT INTO Annotations(GOId, ProteinId, OnthologyId) VALUES(?, ?, ?)");
PreparedStatement getProteinIdQuery =
connection.prepareStatement(
"SELECT Id FROM Proteins WHERE PrimaryUniProtKBAccessionNumber = ?");
connection.setAutoCommit(false);
for(common.Protein protein : network.get_protein_vector()) {
/* Get ProteinId for the current protein from another table and
insert the value into the prepared statement. */
getProteinIdQuery.setString(1, protein.get_primary_id());
ResultSet result = getProteinIdQuery.executeQuery();
result.next();
insertAnnotationsQuery.setLong(2, result.getLong(1));
/* Extract all the other data and add all the tuples to the batch. */
}
insertAnnotationsQuery.executeBatch();
connection.commit();
connection.setAutoCommit(true);
}
这段代码运行良好,程序运行时间约为 30 秒,平均占用 80m 堆空间。因为代码看起来很难看,我想重构它。我做的第一件事是将getProteinIdQuery 的声明移到循环中:
private void loadAnnotations(InteractionNetwork network) throws SQLException {
PreparedStatement insertAnnotationsQuery =
connection.prepareStatement(
"INSERT INTO Annotations(GOId, ProteinId, OnthologyId) VALUES(?, ?, ?)");
connection.setAutoCommit(false);
for(common.Protein protein : network.get_protein_vector()) {
/* Get ProteinId for the current protein from another table and
insert the value into the prepared statement. */
PreparedStatement getProteinIdQuery = // <--- moved declaration of statement here
connection.prepareStatement(
"SELECT Id FROM Proteins WHERE PrimaryUniProtKBAccessionNumber = ?");
getProteinIdQuery.setString(1, protein.get_primary_id());
ResultSet result = getProteinIdQuery.executeQuery();
result.next();
insertAnnotationsQuery.setLong(2, result.getLong(1));
/* Extract all the other data and add all the tuples to the batch. */
}
insertAnnotationsQuery.executeBatch();
connection.commit();
connection.setAutoCommit(true);
}
当我现在运行代码时会发生什么,它需要大约 130m 的堆空间并且需要很长时间才能运行。谁能解释这种奇怪的行为?
【问题讨论】:
标签: java sqlite jdbc transactions prepared-statement