【发布时间】:2013-12-12 19:02:16
【问题描述】:
我在一个简单的 Java 控制台应用程序中使用 PreparedStatement 从 InputStream 中加载大量数据。
这是代码:
public void readStopTimes(CSVReader reader) throws IOException, SQLException {
String insertSql = "INSERT INTO stop_times VALUES (null, ?, ?, ?, ?, ?)";
PreparedStatement statement = db.prepareStatement(insertSql);
String [] nextLine;
long i = 0;
Chronometer chronometer = new Chronometer();
while ((nextLine = reader.readNext()) != null) {
if(i++ != 0) {
statement.setString(1, nextLine[0]);
if(nextLine[1].isEmpty())
statement.setNull(2, Types.TIME);
else
statement.setTime(2, Time.valueOf(nextLine[1]));
if(nextLine[2].isEmpty())
statement.setNull(3, Types.TIME);
else
statement.setTime(3, Time.valueOf(nextLine[2]));
statement.setString(4, nextLine[3]);
statement.setInt(5, Integer.parseInt(nextLine[4]));
statement.addBatch();
}
if(i++ % 1000 == 0) {
statement.executeBatch();
}
if(chronometer.count() > 5000) {
chronometer.restart();
log.debug("Analyzed {} rows", i);
}
}
statement.executeBatch();
db.commit();
}
每 1000 次插入执行批处理,每 5 秒打印一次日志。
从日志中可以看出,该算法在开始时运行得非常快,在前 25 秒内总共计算了超过 400 万行,然后它变慢了,在 5 秒内只添加了 2 行到批次。
我需要插入超过 500 万行,你有更快的替代方案吗?
【问题讨论】:
-
我不知道答案,但为了测试:你能在
statement.executeBatch();之后添加statement = db.prepareStatement(insertSql);吗?
标签: java mysql performance