0

I am new to java. I have recently learned JDBC connection pool in tomcat. To make code reuse I want to share the connection among all servlets without any conflict.

Here My code snippet:

  public class GetConnection{

    private DataSource ds;
    public Connection getConnection(){
      try {
         InitialContext initialContext = new InitialContext();
         Context context = (Context) initialContext.lookup("java:comp/env");
         ds = (DataSource) context.lookup("connpool");
      }
      catch (NamingException e) {

      }
     return ds.getConnection();
    }

 }  

I am calling the getConnection method from different servlets like

            //In servlet1 doGet Method
             Connection conn = GetConnection.getConnection();

Is this right way to do. Or I will get any problem due to concurrent threads.

Manohar Gunturu
  • 676
  • 1
  • 10
  • 23

1 Answers1

0

No, you don't! Do not fiddle manually with the connections. Use at least Commons DbUtils or anything else which hides the complexity. I have seen too many code with stale connections.

Michael-O
  • 18,123
  • 6
  • 55
  • 121