Java SQL 100万行

时间:2016-04-29 17:09:34

标签: java mysql sql

我必须在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行)任何想法?

1 个答案:

答案 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) {
        }
    }
}