Harri,
On 8/5/25 2:40 AM, Harri Pesonen wrote:
Chris's article is fine except that it does not use the try-with-
resources feature of Java language:
try (Connection conn = getConnection()) {
try (Statement stmt = conn.createStatement()) {
try (ResultSet rs = stmt.executeQuery(sql)) {
...
}
}
}
Please check the publication date on that post: it's a few years before
try-with-resources was generally available.
Also, you can use multiple try-with-resources clauses, like this:
try (Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
// Stuff
}
I find try-with-resources less useful with JDBC-related code, as it's
very rarely as simple as the example you have above.
That will make sure that every SQL resource is freed correctly.
Other important thing is that you should free the connection as fast
as possible. Don't make long lasting operations while you have the
connection open. Instead you could read the SQL result to memory,
close the connection, and then do additional work.
+1
Third thing is what Chris is also saying, avoid taking more than one
connection at a time. It will end up in deadlock when you run out of
connections. And it also breaks the previous rule.
This is precisely why I recommend setting maxActive="1" in development
environments.
-chris
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org
For additional commands, e-mail: users-h...@tomcat.apache.org