JDBC 连接池变量上下文可能尚未初始化



我在Netbeans中使用JNDI在Glassfish服务器中创建了一个JDBC连接池(jdbc/WILLIAMSON(,我想在所有servlet中使用它,而不是在每个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();

我创建了一个类DBCONN,并尝试在每个servlet中调用该类的对象,但收到错误"变量上下文可能尚未初始化"。请参阅我的代码如下:

       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();
    }
    }

我把 servlet HOME 中的datasource.getConnection()称为家

.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???

将行更改为 private static InitialContext context = null; 。 编译器警告您,在某些情况下,可能不会创建context

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

最新更新