试试用JDNI连接数据库。其实不晓得JDNI是啥会事。就照猫画虎。配置一个出来看看。网上也找了些资料来看。还是遇到问题了。所以请教各位大哥大姐们!!!
我用的是Oracle10g数据库:数据库名为 ccpa,用户名为 postaudit,密码为 paea;tomcat是6.0 的。
在tomcat的 context.xml 里的配置为:
- XML code
<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里的配置为:
- XML code
<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>
在 项目中代码是:
- Java code
//连接数据库 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; }
最后却是报错的。报的错为:
- Java code
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)
哥哥姐姐们啊!您们说这是咋会事?谢谢!!!
------解决方案--------------------
是server.xml中缺少了<context>元素,你配置的<resource>资源,服务器不知道是给谁、哪个网站用的。
比如一个网站,访问地址你设为http://127.0.0.1:8080/myweb,该站点存放在Tomcat的webapps目录下,名字叫web1。其他数据库连接和JNDI名称就用你的,则应该如下配置:
server.xml中:
- XML code
<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>