我必须在mySQL中使用Java添加1.000.000行,但这个过程很长。我有这段代码:
for(int number=45000000;number<46000000;number++){
query="insert into free(number) values ("+"'"+number+"');";
try {
stmt.executeUpdate(query);
System.out.println(number +" added");
} catch (SQLException e) {
e.printStackTrace();
}
如何加速这个过程? (40分钟= 100.000行)任何想法?
答案 0 :(得分:2)
您可以使用PreparedStatement
和批处理。像,
String query = "insert into free(number) values (?)";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(query);
for (int number = 45000000; number < 46000000; number++) {
ps.setInt(1, number);
ps.addBatch();
if ((number + 1) % 100 == 0) { // <-- this will add 100 rows at a time.
ps.executeBatch();
}
}
ps.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
}