2014-01-21 33 views
1

我一直有这个例外很长一段时间的问题。我试图连接到外部的MySQL数据库,但我不断收到此异常。我看了很多例子,但我仍然没有找到答案。这里是我的代码,请裸记住,这是我使用这个代码,所以请说,如果我错过了一些东西:jdbc javax.naming.NameNotFoundException

<?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; 
} 

用户名,密码,db网址和连接名称已被编辑,但其余都是正确的。

+0

你能分享你的完整堆栈跟踪吗? – mprabhat

+0

也有你在web.xml中添加资源引用 – mprabhat

+0

“<资源引用> JDBC/&&&&&& 的javax.sql.DataSource 集装箱 '这就是web.xml中的内容 –

回答

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"); 

问候。

+0

我应该补充一点,我已经尝试过这一点,我只是试了一遍。这对我不起作用,同样的错误。 –

相关问题