title: Java, JDBC: Does closing a PreparedStatement also free up its memory footprint in the database connection?
body: <p>As I understand it, each time a <code>PreparedStatement</code> is initialized, the statement gets cached in the memory allocated for the database connection. Therefore, if one initializes excessive <code>PreparedStatement</code> variables there is a risk of overflowing the memory available to the connection. </p>
  
  <ol>
  <li><p>Is the cached memory freed by calling <code>close()</code> on the <code>PreparedStatement</code> instances?</p></li>
  <li><p>Do two <code>PreparedStatement</code> containing identical SQL create duplicate caching events, or is the database smart enough not to cached a new instance of a duplicate <code>PreparedStatement</code>?</p></li>
  </ol>
  
  <p>Example 1, would this overflow connection memory?:</p>
  
  <pre><code>while (true) {
      PreparedStatement ps = connection.prepareStatement("SELECT id + ? FROM tbl");
      ps.setDouble(1, Math.random());
      ps.executeQuery();
      ps.close();
  }
  </code></pre>
  
  <p>If it would, then what about this?:</p>
  
  <pre><code>while (true) {
      PreparedStatement ps = connection.prepareStatement("SELECT id FROM tbl");
      ps.executeQuery();
      ps.close();
  }
  </code></pre>