java—获取noinitialcontextexception以尝试连接到mysql数据库

qgelzfjb  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(237)

我在做一个项目,我正在尝试使用连接池与mysql和java。我在context.xml和web.xml中添加了一些数据库信息。我用的是Tomcat8。
上下文:

<Resource name="jdbc/myDb"
          auth="Container"
          type="javax.sql.DataSource"
          username="tm"
          password="tm"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/myDb"
          maxWaitMillis="10000"
          maxTotal="8"
          maxIdle="4" />
</Context>

网状物:

<resource-ref>
        <description>MySql Datasource for MyDb</description>
        <res-ref-name>jdbc/myDb</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

这是我的connectionmanager,在这里我得到noinitialcontextexception:

public class ConnectionManager {
   private static final String DATASOURCE = "jdbc/myDb";
   private static ConnectionManager connMgrInst = null;
   private DataSource ds = null;

   public static synchronized ConnectionManager getInst() {
      if (connMgrInst == null) 
            connMgrInst = new ConnectionManager();

      return connMgrInst;
   }
   private ConnectionManager() {
      try {
         Context ctx = new InitialContext();
         ds = (DataSource) ctx.lookup("java:comp/env/" + DATASOURCE);
      } catch (NamingException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
      }
   }

   public Connection getConn() {
      Connection retVal = null;
      try {
         retVal = ds.getConnection();//get a connection from the pool
      } catch (SQLException ex) {
         Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
      }

      return retVal;
   }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题