title: JDBC Batch Insert OutOfMemoryError
body: <p>I have written a method <code>insert()</code> in which I am trying to use JDBC Batch for inserting half a million records into a MySQL database:</p>
  
  <pre class="lang-java prettyprint-override"><code>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);
      }
  }
  </code></pre>
  
  <p>But whenever I try to run this method, I get the following error:</p>
  
  <pre><code>java.lang.OutOfMemoryError: Java heap space
      com.mysql.jdbc.ServerPreparedStatement$BatchedBindValues.&lt;init&gt;(ServerPreparedStatement.java:72)
      com.mysql.jdbc.ServerPreparedStatement.addBatch(ServerPreparedStatement.java:330)
      org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:171)
  </code></pre>
  
  <p>If I replace <code>ps.addBatch()</code> with <code>ps.executeUpdate()</code> and remove <code>ps.executeBatch()</code>, it works fine, though it takes some time. Please let me know if you know if using Batch is appropriate in this situation, and if it is, then why does it give <code>OurOfMemoryError</code>?</p>
  
  <p>Thanks</p>