【发布时间】:2012-11-27 08:19:12
【问题描述】:
谁能建议将数千/数十万行插入 mysql 表的最快方法?现在我正在使用 executeBatch,但我想知道是否有更快的方法来做到这一点?
try {
Connection con = dataSource.getConnection();
Statement statement = con.createStatement();
for(int i = 0; i < value; i++) {
DateTime f = DateTime.now().minusDays(i % 28);
String q1 = "INSERT INTO table1_test (txid, time, badgeid, event_type, sensorid, shift, unitid) VALUES ('"+i+"', '"+f.toString("yyyy-MM-dd HH:mm:ss")+"', 'NA', 'EN', '100', 'A', '1')";
String q2 = "INSERT INTO table2_test (txid, time, badgeid, sensorid, shift, unitid) VALUES ('"+i+"', '"+f.toString("yyyy-MM-dd HH:mm:ss")+"', 'NA', '100', 'A', '1')";
String q3 = "INSERT INTO table3_test (txid, badgeid, time, shift, compliant, sensorid, unitid) VALUES ('"+i+"', 'NA', '"+f.toString("yyyy-MM-dd HH:mm:ss")+"', 'A', 1, '100', '1')";
statement.addBatch(q1);
statement.addBatch(q2);
statement.addBatch(q3);
}
statement.executeBatch();
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
【问题讨论】:
-
考虑在一个插入语句中将多行合并到同一个表中。否则,Prepared Statements 是您的最佳选择。
标签: java mysql optimization