title: Java SQL query memory leak
body: <p>I have an application that iterates over an amount of resultSets and queries additional information for every row from a different table.</p>
  
  <p>The rough structure is like this:</p>
  
  <pre><code>public void main(String[] args) {
      ResultSet result = database.connection.createStatement()
                             .executeQuery("SELECT * FROM entities");
      ArrayList&lt;Entity&gt; entities = new ArrayList&lt;Entity&gt;();
      while (result.next() {
          Entity entity = EntityFactory.createById(result.getInt("id"));
          entities.add(entity);
      }
  }
  
  // EntityFactory
  public static Entity createById(int id) {
      StringBuilder sql = new StringBuilder("SELECT * FROM sampling_data WHERE id = ")
                              .append(id);
      ResultSet result = database.connection.createStatement()
                              .executeQuery(sql.toString());
      result.first();
      EntityData data = new EntityData(25);
  
      for (int sample = 1; sample &lt;= 25; sample++) {
          String sample_R = new StringBuilder("sample_")
                                .append(sample).append("_R").toString();
          String sample_G = new StringBuilder("sample_")
                                .append(sample).append("_G").toString();
          String sample_B = new StringBuilder("sample_")
                                .append(sample).append("_B").toString();
  
          int r = resultSet.getInt(sample_R);
          int g = resultSet.getInt(sample_G);
          int b = resultSet.getInt(sample_B);
  
          data.add(r, g, b);
      }
  
      return new Entity(data);
  }
  </code></pre>
  
  <p>Which results in a OutOfMemoryException.</p>
  
  <p>How can I make the loop (or the whole methods) more memory efficient?</p>