The order in which you ``++close++`` database-releated resources is crucial. Close a ``++Connection++`` first, and depending on the database pooling in use, you may no longer be able to truly reach its ``++Statement++``s and ``++ResultSet++``s to close them, even though the calls are made and execute without error.


== Noncompliant Code Example

----
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
  conn = DriverManager.getConnection(connectionString);
  ps = conn.prepareStatement(query);
  rs = ps.executeQuery();
  // ...
} finally {
  try { 
    if (conn != null) {
      conn.close();   // Noncompliant; close this last
    }
  } catch (Exception e) {};
  try { 
    if (ps != null) {
      ps.close(); 
    }
  } catch (Exception e) {};
  try { 
    if (rs != null) {
      rs.close(); 
    }
  } catch (Exception e) {};
}
----


== Compliant Solution

----
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
  conn = DriverManager.getConnection(connectionString);
  ps = conn.prepareStatement(query);
  rs = ps.executeQuery();
  // ...
} finally {
  try { 
    if (rs != null) {
      rs.close(); 
    }
  } catch (Exception e) {};
  try { 
    if (ps != null) {
      ps.close(); 
    }
  } catch (Exception e) {};
  try { 
    if (conn != null) {
      conn.close(); 
    }
  } catch (Exception e) {};
}
----


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
