我已经编写了一个方法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.executeUpdate()
替换ps.addBatch()
并删除ps.executeBatch()
,它可以正常工作,尽管这需要一些时间。请让我知道你是否知道在这种情况下使用批处理是否合适,如果合适,那么为什么它会给出OurOfMemoryError
谢谢
发布于 2010-02-09 16:34:52
addBatch
和executeBatch
为您提供了执行批插入的机制,但是您仍然需要自己执行批处理算法。
如果您只是将每个语句都堆放到同一批处理中,那么您将耗尽内存。您需要执行/清除每个n
记录的批处理。n
的价值取决于您,JDBC不能为您做出决定。批处理的大小越大,运行速度就越快,但是如果批处理太大,就会导致内存匮乏,速度变慢或失败。这取决于你有多少内存。
例如,从批处理大小为1000开始,然后使用不同的值进行实验。
final int batchSize = 1000;
int count = 0;
for(String s : names ) {
ps.setInt(1, nameListId);
ps.setString(2, s);
ps.addBatch();
if (++count % batchSize == 0) {
ps.executeBatch();
ps.clearBatch(); //not sure if this is necessary
}
}
ps.executeBatch(); // flush the last few records.
https://stackoverflow.com/questions/2227596
复制相似问题