Closing connection in finally block

Posted on 2004-11-12
Last Modified: 2007-12-19

Is it a recommend practice to close db connection in finally block?

Here's my code.

public class ChargeService {

      private Connection conn = null;
      private PreparedStatement statement = null;
      private ResultSet rs = null;
      private String sqlStr = "";

      public boolean isCreditEnough(int groupId, String phoneNumber) {

            boolean isEnough = false;
            int creditBalance = 0;
            int creditToCharge = 0;

            try {
                  conn = DriverManager.getConnection(DbConfig.dbUrl);

                  sqlStr = "SELECT totalCredit, credit" + " FROM"
                              + " chat_users, chat_credits" + " WHERE" + " groupId="
                              + groupId + " AND" + " phoneNumber='" + phoneNumber + "'";
                  statement = conn.prepareStatement(sqlStr);
                  rs = statement.executeQuery();

                  while ( {
                        creditBalance = rs.getInt("totalCredit");
                        creditToCharge = rs.getInt("credit");

                  if (creditBalance - creditToCharge >= 0) {
                        isEnough = true;

                  } else {
                        isEnough = false;


            } catch (SQLException e) {
                  throw new ChatException(getClass().toString(), e);

            } finally {


            return isEnough;


BTW, i use DBUtils from Jakarta Common project. So, my problem is,

-I'm got problems with closing my db connections, based on my connection threads i see in my mysqladmin it keeps getting more and more.

My question is,
-Is this a problem of DbUtils.closeQuietly(conn) not executing or my code problem?
-what is the recommend approach to close connection?


Question by:mwhc
    LVL 2

    Expert Comment

    I'll use this code instead:

          Connection conn=null;
    }catch(SQLException SQLE){
          throw new Exception(SQLE.getMessage());
          }catch(SQLException SQLE){}

    The same try/catch for a ResultSet or a CallableStatement/PreparedStatement
    LVL 6

    Expert Comment

    I think you should explicitly call the Dispose method of the connection object to close unmanaged resources. Don't know about these Jakarta utils, but check if they call the Dispose method.
    LVL 2

    Expert Comment


    The code that I posted is working and answers the question. What type of recomendation do you need?
    Help me to understand please.

    LVL 6

    Accepted Solution

    Closing a connection is not enough to clear unmanaged resources. These are later handled by the GC. The dispose method of the connection object is required to free resource immediately. I feel I deserve at least some points.
    LVL 2

    Expert Comment

    I agree abdullah

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    haveThree challenge 22 89
    bunnyEars challenge 6 45
    parentbit challenge 3 37
    strCopies  challenge 17 60
    A short article about problems I had with the new location API and permissions in Marshmallow
    If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now