1

I am using BoneCp connection pool. I have a question that where to specify JDBC connection objects such that It should not give errors like ResultSet is closed or Connection is closed.

I am doing as shown below:(code snippet)

          public Class GetTable extends HttpServlet {
                 Connection con = null;                         
                 Statement stmt = null;
                 ResultSet rs = null; 
            protected void doPost(HttpServletRequest req,HttpServletResponse res)
                {
                 con = ConnectionManager.getConnectionPool().getConnection();       
                 //initializing stmt,rs 
                 //close con,stmt,rs using try and catch  
                }    

           }

Is this good way or I have to define all JDBC objects inside doPost?

For every request a new Instance of servlet is created then how I have to manage JDBC objects without errors.

Manohar Gunturu
  • 676
  • 1
  • 10
  • 23

2 Answers2

0

No, that's not a good way at all.

You're using instance variables, and the same servlet objects is used to serve all the requests coming to that servlet. So, if request 1 comes in, it will open a connection and assign it to the instance variable conn.

Concurrently, request 2 comes in, and will thus also open a connection and assign it to the same conn variable. request 1, will thus start using the connection opened for request 2. When request 1 ends, it will (hopefully) close the connection, which will thus also close the connection used by request 2.

These all should be local variables.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • So Instance is created only for doPost method, not for whole servlet. Am I right? – Manohar Gunturu Aug 27 '15 at 07:07
  • In both cases, an instance will be created. The difference is that two threads won't share the same variables and won't work on each other's toes if you use local variables. Because each method invocationhas its own local variables, not shared with any other method invocation. – JB Nizet Aug 27 '15 at 07:10
0

It is better to use a singleton connection factory class to service connection. And also after java 8 if u open conneciton inside try(...) it closes your connection after try block end.