【问题标题】:jdbc javax.naming.NameNotFoundExceptionjdbc javax.naming.NameNotFoundException
【发布时间】:2014-01-21 16:10:17
【问题描述】:

长期以来,我一直对这个异常有疑问。我正在尝试连接到外部 mysql 数据库,但我不断收到此异常。我看了很多例子,但我仍然没有找到答案。这是我的代码,请记住,这是我用于此的所有代码,所以如果我遗漏了什么,请说:

    <?xml version="1.0" encoding="UTF-8"?>
<context>
    <!-- Registers Database with JNDI Naming Service as a pooled DataSource -->
<Resource 
        name="jdbc/DBNAME" 
        auth="Container" 
        type="javax.sql.DataSource" 
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        testWhileIdle="true"
        testOnBorrow="true"
        testOnReturn="false"
        validationQuery="SELECT 1"
        validationInterval="30000"
        timeBetweenEvictionRunsMillis="30000"
        maxActive="100" 
        minIdle="10" 
        maxWait="10000" 
        initialSize="10"
        removeAbandonedTimeout="60"
        removeAbandoned="true"
        logAbandoned="true"
        minEvictableIdleTimeMillis="30000" 
        jmxEnabled="true"
        jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
        username="****" 
        password="********"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://****:3306/****"/>

</context>

这是我调用它的代码:

try
{
    InitialContext ic = new InitialContext();
    DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/DBNAME");
    Connection c = ds.getConnection();
    return c;
}
catch(NamingException ne)
{
    System.out.println(ne.toString());
    return null;
}
catch (SQLException se) 
{
    System.out.println(se.toString());
    return null;
}

用户名、密码、数据库 url 和连接名称已被编辑,但其余部分正确。

【问题讨论】:

  • 你能分享你完整的堆栈跟踪吗?
  • 您是否在 web.xml 中添加了资源引用
  • 'jdbc/&&&&&&javax.sql.DataSourceContainer ' 这是 web.xml 中的内容
  • 您的 res-ref-name 应该与 name 相同。请同时创建 jdbc/chitchat 或 jdbc/DBNAME
  • 是的,它们都是一样的,我之前刚刚修改了这个名字。

标签: java tomcat jdbc jndi


【解决方案1】:

来自 Tomcat 文档:

http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html

尝试使用此代码:

Context ic= new InitialContext();
Context envCtx = (Context) ic.lookup("java:comp/env");

DataSource ds = (DataSource)envCtx.lookup("jdbc/DBNAME");

问候。

【讨论】:

  • 我应该补充一点,我已经尝试过了,我又试了一次。这对我不起作用,同样的错误。
猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 2018-11-02
  • 2017-07-17
  • 2012-10-07
  • 1970-01-01
  • 2021-01-29
  • 2011-09-22
  • 2011-04-24
相关资源
最近更新 更多