I have a class that uses a static
initialization block to set up a connection to a database. The class has many public static
methods that query the db. I would like to properly close this connection in a static
block that executes just before the program terminates, kind of like a finally
block in a try/catch
. I am almost certain that something like this does not exist in Java. Is my best option to open and close the connection with each query?

- 12,717
- 29
- 108
- 202

- 41
- 3
-
possible duplicate of [How to ensure a piece of code is run before exiting a java application](http://stackoverflow.com/questions/13754263/how-to-ensure-a-piece-of-code-is-run-before-exiting-a-java-application) – Sachin Gupta Jul 21 '15 at 05:05
-
You need to post the code really . But generally speaking the a static connection variable once initialized will remain available through out the life of application. – Shahzeb Jul 21 '15 at 05:05
-
possible duplicate of http://stackoverflow.com/questions/30936623/try-catch-finally-block-in-java?rq=1 – Spartan Jul 21 '15 at 05:06
-
@SachinGupta no it's not a duplicate he is asking a different topic. How is cricket going for you :) (I know lame but could not resist) – Shahzeb Jul 21 '15 at 05:07
-
@thanga not a duplicate of that either. Come on people. – Shahzeb Jul 21 '15 at 05:08
-
Post the code you have . People on this forum can correct if for you without that every one is just guessing. – Shahzeb Jul 21 '15 at 05:10
-
1Probably a shutdown hook..http://javapapers.com/core-java/jvm-shutdown-hook/ – RP- Jul 21 '15 at 05:11
-
3The only you "might" know when the JVM shuts down is through a shut down hook, BUT, this assumes a normal shutdown has occurred. Generally speaking a better solution might be to either create short lived instances of the `Connection` as you need them and close them when you're done or use a connection pool of some kind – MadProgrammer Jul 21 '15 at 05:14
-
If you have multiple number of queries, running from a single thread(i guessed), then why do you want to open and close the connections repetitive times? This would only increase unwanted problems(db dependent). *Create a `singleton` instead which opens the connections for each database once, and after you finish all operation, just call a dispose-off method for your Statements, ResultSets and Connections* – mustangDC Jul 21 '15 at 05:19
-
Huh. I'm kinda stuck on a static initializer making a DB connection (or connection pool). I'm asking because I'm wondering if failure means application re-start. Am I misguided? – David J. Liszewski Jul 21 '15 at 05:55
-
I guess using `static` here would be the first choice, as the user needs single db connection with multiple queries (`lol :), we are playing a guessing game, as the user has not proved much details about DB`) – mustangDC Jul 21 '15 at 08:44
4 Answers
Have a look at this : Running a method when closing the program?
You could try writing the code to close connection in this method.
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
//code to close connection
}
}, "Shutdown-thread"));
}
-
The above code works fine when the application exits normally. If virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run. – Sridhar Jul 21 '15 at 05:25
-
The question is **Is my best option to open and close the connection with each query?** – mustangDC Jul 21 '15 at 05:29
-
If you have too many queries, its not good to open and close connection with every query. It wil increase your lines of code and cause unnecessary overhead. Using a shutDownHook can reduce all that .. – Ridhima Jul 21 '15 at 05:35
Opening and closing the connection for every query will cause an additional overhead on system making the application slow.
You could surround the final query of your DB program with try catch blocks instead and release the connection in the finally clause (for the last query of your program).
NOTE: If the JVM terminates before the main thread finishes execution, i.e. System.exit() executes, the subsequent code and the finally block won't be executed.

- 2,239
- 20
- 28
public class JdbcDBManager {
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public JdbcDBManager(String url, String user, String pass) throws ClassNotFoundException, SQLException {
Class.forName("org.gjt.mm.mysql.Driver");
this.connection = DriverManager.getConnection(url, user, pass);
}
public void close() {
try {if (this.preparedStatement != null)this.preparedStatement.close();} catch (Exception e) {e.printStackTrace();}
try {if (this.resultSet != null)this.resultSet.close();} catch (Exception e) {e.printStackTrace();}
try {if (this.connection != null)this.connection.close();} catch (Exception e) {e.printStackTrace();}
}
public void customerInsert(Customer customer) {
try {
String query = "INSERT INTO customer(email,product) VALUES(?,?,?,?,?)";
this.preparedStatement = this.connection.prepareStatement(query);
this.preparedStatement.setString(1, customer.getEmail());
this.preparedStatement.setString(3, customer.getProduct());
} catch (Exception e) { e.printStackTrace();}
}}
You can create an object for each Database and when you are finally done processing close it.
public class test {
public static void process() throws ClassNotFoundException, SQLException {
JdbcDBManager customerDB = new JdbcDBManager(JdbcURL.URL, JdbcURL.USER, JdbcURL.PASS);
try {
customerDB.insertCustomer(Customer customer);
doSomething(customerDB); // Pass db object as a parameter
} finally { customerDB.close();} // close it when you are finally done
}
doSomething(JdbcDBManager customerDB){
---------------------------
--process info in db-------
} }
This way you open connection for one time and close when process are finally finished

- 131
- 1
- 12
Is my best option to open and close the connection with each query? Ans : NO
I would suggest you to follow:
Singleton Class
for opening the connection, something like this :
public class connectDB {
static Connection conn = null;
public static Connection getConnection(){
if (conn != null) return conn;
String connString = "DATABASE ACCESS URL HERE";
return getConnection(connString);
}
private static Connection getConnection(String conString){
try{
Class.forName("LOAD DRIVER HERE");
String uname = "DB USERNAME";
String pass = "DB PASSWORD";
conn = DriverManager.getConnection(conString, uname, pass);
}
catch(Exception e){
//Handle Exceptions
e.printStackTrace(); //<--Retrieves the error/Exception for you
}
return conn;
}
}
And close the connection with something like :
public static void closeConnection(Connection conn) {
try {
conn.close();
}
catch (SQLException e) {
//Handle Exception Here
}
}
Just call
conn = connectDB.getConnection()
for connection and the other one for closing, preferable in a finally

- 945
- 1
- 12
- 33