O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

There's more...

It is good practice to think about closing the connection as soon as you create it. The way to do this is using the try-with-resources construct, which ensures that the resource is closed at the end of the try...catch block:

try (Connection conn = getDbConnection()) {  // code that uses the connection to access the DB} catch(Exception ex) {   ex.printStackTrace();}

Such a construct can be used with any object that implements the java.lang.AutoCloseable or java.io.Closeable interface. 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required