-1

I created a JDBC connection pool (jdbc/WILLIAMSON) in Glassfish server using JNDI in Netbeans, I want to use this in all servlets so instead of writing the following code in every servlet

     InitialContext context = new InitialContext();
        //The JDBC Data source that we just created
        DataSource datasource = (DataSource) 
         context.lookup("jdbc/WILLIAMSON");
         Connection connection = null;
          connection = ds.getConnection();

I created a class DBCONN and tried to call an object of this class in every servlet but getting error "variable context might not have been initialized". See my code is below:

       public final class DBCONN {    
       private static final InitialContext context;
       private static final DataSource datasource;
        static{              
          try {
              context = new InitialContext();
                 datasource=(DataSource) context.lookup("jdbc/WILLIAMSON");
          } catch (NamingException ex) {
              Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE, 
          null, ex);
          }
    }
   private DBCONN() {
      //  I am confused how to use this method, pls guide me
    }// ERROR HERE VARIABLE context MIGHT NOT HAVE BEEN INITIALIZED

    public static Connection getConnection() throws SQLException {
    return datasource.getConnection();
    }

    }

I'm calling the datasource.getConnection() in servlet HOME.java

       DBCONN datasource = new DBCONN();
        Connection connection = null;
        connection = datasource.getConnection();// I am accessing a static 
       method so warning coming accessing static method getConnection(), how 
        to avoid it???
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

Change the line to private static InitialContext context = null;. The compiler is warning you that under certain circumstances, context might not be created.

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
-2
static{
context = new InitialContext(); 
try { 
datasource=(DataSource) context.lookup("jdbc/WILLIAMSON");
} catch (NamingException ex) { 
Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE, null, ex);            }