Java finally static block
I have a class that uses an init block static
to set up a database connection. The class has many methods public static
that ask for db. I would like to properly close this connection in a block static
that is executed just before the program terminates, sort of like a block finally
in try/catch
. I'm pretty sure something like this doesn't exist in Java. Is it my best way to open and close a connection with every request?
source to share
Look at this: Running a method on program close?
You can try writing some code to close the 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"));
}
source to share
Opening and closing a connection for each request will cause additional overhead on the system, making the application slow.
You can concatenate the final request of your DB program using catch blocks and release the connection in a finally clause (for the last request of your program).
NOTE. If the JVM exits before the main thread finishes, that is, System.exit () is executed, the subsequent code and finally block will not be executed.
source to share
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, 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 the connection in one go and close it when the process is finally complete.
source to share
Is it my best way to open and close a connection with every request? Ans: NO
I suggest you follow:
Singleton Class
to open a 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()
to connect and another to close, preferably atfinally
source to share