2021-04-28 16:49:39 +02:00
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.
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== 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) {};
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== 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) {};
}
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]