首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JDBC批量插入OutOfMemoryError

JDBC批量插入OutOfMemoryError
EN

Stack Overflow用户
提问于 2010-02-09 16:05:21
回答 1查看 18K关注 0票数 23

我已经编写了一个方法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

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-02-09 16:34:52

addBatchexecuteBatch为您提供了执行批插入的机制,但是您仍然需要自己执行批处理算法。

如果您只是将每个语句都堆放到同一批处理中,那么您将耗尽内存。您需要执行/清除每个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.
票数 47
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2227596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档