我编写了一个名为insert()
的方法,其中我正在尝试使用JDBC Batch将50万条记录插入到MySQL数据库中:
public void insert(int nameListId, String[] names) {
String sql = "INSERT INTO name_list_subscribers (name_list_id, name, date_added)" +
" VALUES (?, ?, NOW())";
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
for (String s : names ) {
ps.setInt(1, nameListId);
ps.setString(2, s);
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
closeDbResources(ps, null, conn);
}
}
但是每当我尝试运行这个方法时,我都会遇到以下错误:
java.lang.OutOfMemoryError: Java heap space
com.mysql.jdbc.ServerPreparedStatement$BatchedBindValues.<init>(ServerPreparedStatement.java:72)
com.mysql.jdbc.ServerPreparedStatement.addBatch(ServerPreparedStatement.java:330)
org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:171)
如果我将ps.addBatch()
替换为ps.executeUpdate()
并删除ps.executeBatch()
,那么它可以正常工作,尽管需要一些时间。如果在这种情况下使用Batch是合适的,请让我知道,如果是的话,为什么会出现OutOfMemoryError
? 感谢!
clearBatch()
,似乎没有帮助。它仍然会导致OOM(内存溢出)。有更好的方法来解决这个问题吗? - Daredevilps.clearBatch()
。在StatementImpl.executeBatchInternal()
中的每个ps.executeBatch()
内部调用它。 - v.ladynev