James James - 2 months ago 15
Java Question

Try with resources JDBC queries

I am working through a swing tutorial that interacts with a database using JDBC. The tutorial uses a different approach than what I have seen in the past when interacting with databases.

Previously, one method was used for the update or query. A try with resources block was used to create a connection object and statements, the query was executed and the connection closed automatically afterwards. I believed this was the correct way.

In this swing tutorial, there is a method that creates the connection, a method to perform the query and a method to close the connection. As I see it, the connection to the database is being kept open for the duration of the application life-cycle. Is this common practice? This is a tutorial from 2013 so I thought it may just be outdated.

I am very new to JDBC an would like to know what the recommended approach is now.

Thanks

Apologies if my question is ambiguous. What I was mostly concerned with was whether I should open and close a connection for each operation or just keep the connection open as long as my application was running.

Is there a benefit to separating connect and disconnect to their own methods?

Answer

A try-with-resources is necessary if there are multiple users (threads) competing for the resource, such as in a multi-user web application. In these cases the close() won't actually close the connection, it will just return it to the pool so it's available for other threads to check out.

If you're creating a single user Swing application, it's not harmful to keep a Connection open for a longer time as you're the only one using it.