【发布时间】:2015-08-12 10:43:06
【问题描述】:
我使用JDBC",我写了下面的“insertRecord”方法,它应该被多次调用并将记录插入数据库表中。当我为每 500 条记录运行代码时“批次的大小”
这需要 20 秒,而且速度非常慢,因为该代码应该在不同的 xml 文件上运行 30 次以隔离它们并将一些数据插入到数据库表中。
对于如何优化代码以达到最佳性能有什么建议吗?
CreateTable 方法
public void CreateTable(String tableName) throws SQLException, ClassNotFoundException {
if (this.isTableExists(tableName)) {
Log.i(TAG, "CreateTable", "table: ["+tableName+"] already exists.");
this.connInsert = this.getConnection();
this.connInsert.setAutoCommit(true);
this.psInsert = this.connInsert.prepareStatement("insert into "+this.TABLE_NAME+" ("+this.NODE_ID_COL+", "+this.LAT_COL+", "+this.LNG_COL+", "+this.XML_PATH_COL+") values (?, ?, ?, ?)");
} else {
Log.i(TAG, "CreateTable", "table: ["+tableName+"] does not exist, will be created");
Connection conn = this.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate(this.sqlTable);
stmt.close();
conn.close();
this.connInsert = this.getConnection();
this.connInsert.setAutoCommit(true);
this.psInsert = this.connInsert.prepareStatement("insert into "+this.TABLE_NAME+" ("+this.NODE_ID_COL+", "+this.LAT_COL+", "+this.LNG_COL+", "+this.XML_PATH_COL+") values (?, ?, ?, ?)");
}
}
插入记录方法
public void insertRecord(Record rec) throws SQLException, ClassNotFoundException {
if (this.isTableExists(this.TABLE_NAME)) {
this.psInsert.setString(1, rec.getNodeID());
this.psInsert.setString(2, rec.getLat());
this.psInsert.setString(3, rec.getLng());
this.psInsert.setString(4, rec.getPath());
this.psInsert.addBatch();
if (++this.batchCnt == SysConsts.BATCH_SIZE) {
this.psInsert.executeBatch();
this.batchCnt = 0;
Log.d(TAG, "insertRecord", SysConsts.BATCH_SIZE+" records inserted.");
}
} else {
Log.e(TAG, "insertRecord", "table: ["+this.TABLE_NAME+"] does not exist");
}
}
fluch 方法,用于刷新批处理中的剩余记录
//this method should be called in the end of the code to flush the remaining records in the batch
public void flush() throws SQLException {
this.psInsert.executeBatch();
this.psInsert.close();
this.connInsert.close();
Log.d(TAG, "insertRecord", "the rest of the records flushed into data base table.");
}
【问题讨论】: