Close ResultSet Object Explicitly Before Closing Connection when Using Servlets

Most Java programmers close a connection with database directly without closing the ResultSet. This is okay with standalone Java programs, where the Java compiler automatically closes the Resultset for you, but when we deploy this code in a servlet, then we are not guaranteed this behavior.

For example, take a look at the following code snippet:

 public void doGet ( HttpServletRequest req, HttpServletResponse res )                         throws ServletException, IOException  {        Connection con = null;        try        {            Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );            con = DriverManager.getConnection("jdbc:odbc:issue","super","super");            ResultSet  rs   = stmt.executeQuery( "SELECT * FROM person_id_table" );            /* More Code Here */        }        catch( SQLException e )        {        }         finally        {           try            {                  if( con != null )                  {                     con.close();  // Resultset not closed prior to this statement                 }           }           catch( SQLException ignored )             {           }         }   } 

This code looks perfectly fine. The problem arises when we deploy the code using JSDK1.1 Servlet Engine. It leads to a Windows NT Access Violation Error. The same runs perfectly all right with ServletExec Servlet Engine. So to be safe, remember to close the ResultSet explicitly before closing the Connection like in the following code:

 public void doGet ( HttpServletRequest req, HttpServletResponse res )                         throws ServletException, IOException  {        Connection con = null;        ResultSet rs = null;        try        {            Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );            con = DriverManager.getConnection("jdbc:odbc:issue","super","super");            rs   = stmt.executeQuery( "SELECT * FROM person_id_table" );            /* More Code Here */        }        catch( SQLException e )        {        }         finally        {           try            {                  if( con != null )                  {                     rs.close();                    con.close(); // Resultset closed prior to this statement.                 }           }           catch( SQLException ignored )             {           }         }   } 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: