试试用JDNI连接数据库。其实不晓得JDNI是啥会事。就照猫画虎。配置一个出来看看。网上也找了些资料来看。还是遇到问题了。所以请教各位大哥大姐们!!! 
    我用的是Oracle10g数据库:数据库名为 ccpa,用户名为 postaudit,密码为 paea;tomcat是6.0 的。
  在tomcat的 context.xml 里的配置为:
    
<Resource
name="ccpa"
auth="Container"
type="javax.sql.DataSource"
 
driverClass="oracle.jdbc.driver.OracleDriver"
username="postaudit"
password="paea"
jdbcUrl="jdbc:oracle:thin:@127.0.0.1:1521:ccpa"
idleConnectionTestPeriod="0"
idleMaxAge="60"
partitionCount="1"
maxConnectionsPerPartition="5"
minConnectionsPerPartition="2"
acquireIncrement="2"
poolAvailabilityThreshold="20"
connectionTimeout="60000"
/>
在项目的web.xml里的配置为: <resource-ref> 
    <description>DB Connection</description> 
    <res-ref-name>ccpa</res-ref-name> 
    <res-type>javax.sql.DataSource</res-type> 
    <res-auth>Container</res-auth> 
    <res-sharing-scope>Shareable</res-sharing-scope>
    
</resource-ref> 在 项目中代码是:
//连接数据库
public Connection getConnection(){
Connection conn=null;
try {
String jndi="ccpa";
Context ctxt=new InitialContext();
DataSource ds=(DataSource) ctxt.lookup(jndi);
System.out.println("XXXXXXXXXXXXXXX"+ds);
try {
conn=ds.getConnection();      
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return conn;
}
最后却是报错的。报的错为:
javax.naming.NameNotFoundException: Name ccpa is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:152)
at javax.naming.InitialContext.lookup(InitialContext.java:392)   哥哥姐姐们啊!您们说这是咋会事?谢谢!!!

解决方案 »

  1.   

    是server.xml中缺少了<context>元素,你配置的<resource>资源,服务器不知道是给谁、哪个网站用的。比如一个网站,访问地址你设为http://127.0.0.1:8080/myweb,该站点存放在Tomcat的webapps目录下,名字叫web1。其他数据库连接和JNDI名称就用你的,则应该如下配置:server.xml中:<Context path="/myweb" docBase="web1" debug="0" crosscontext="true" reloadable="true">
    <Resource name="jdbc/sample_db" auth="Container"
    type="javax.sql.DataSource" maxActive="20" maxIdle="5" maxWait="10000"
    username="postaudit"
    password="paea"
    driverClassName="oracle.jdbc.driver.OracleDriver"
    url="jdbc:oracle:thin:@127.0.0.1:1521:ccpa"/>
    </Context>
    web.xml中如下配置:<resource-ref>
         <description>JNDI JDBC DataSource</description>
         <res-ref-name>jdbc/ccpa</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
    </resource-ref>
    调用的代码如下:Context initContext=new InitialContext();//得到拥有当前java运行环境资源的上下文
    Context envContext=(Context)initContext.lookup("java:/comp/env");//从该上下文对象中得到数据源头
    DataSource ds=(DataSource)envContext.lookup("jdbc/ccpa");//从数据源中的到一个连接对象
    Connection con = ds.getConnection()
    ……
      

  2.   

    更正一下:
    server.xml中第二行:<Resource name="jdbc/sample_db"更正为:<Resource name="jdbc/ccpa"和你的web.xml中配置的一致.