日期:2014-05-17  浏览次数:20664 次

大大们,求助啊,弄了一早上都搞不定。。
我做了一个servlet的web小程序练手,但是数据库这一块始终出错,找不到原因,弄得我身心疲惫啊,请各位大神帮我看看啊.

下面是web.xml的设置
<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/DBtest</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
  </resource-ref>

下面是context.xml才设置
<!-- The contents of this file will be loaded for each web application -->
  <Context>
  <Resource name="jdbc/DBtest" auth="Container"
  type="javax.sql.DataSource"
  maxActive="30" maxIdle="10" maxWait="10000"
  driverClassName="com.mysql.jdbc.Driver"
  url="jdbc:mysql://localhost:3306/hsp"
  username="root" password="root" />
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
  </Context>


下面是连接数据库的代码:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/hsp");
con = ds.getConnection();

}catch(Exception ex){
ex.printStackTrace();
}
  if(con == null){
   
  System.out.println("con is null!!!!!!!!!!!1");
  }
  System.out.println("datasource set over!");
try{
  System.out.println("statement set!");

stm = con.createStatement();
System.out.println("statement set over!");
}catch(Exception ex){
ex.printStackTrace();
}




我发现con始终是空的,这让我蛋疼了,始终改不出来,求帮助啊!!

------解决方案--------------------
你这里有两个文档
第一,数据源你配置的名称是jdbc/DBtest 但是在程序里面你查找的却是java:comp/env/jdbc/hsp,需要改成java:comp/env/jdbc/DBtest

第二,你需要确保将mysql的jdbc驱动包放到tomcat/lib 这个包下

你这样处理一下,看看还有报错么
------解决方案--------------------
你认真看看我给你在2楼的回帖,看帖都不认真……

把你的mysql的jdbc驱动包放到 tomcat所在目录的lib目录下面 ,然后重新启动tomcat ,看看报什么错误

探讨

现在是这个问题了:
Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
我在web-inf里的lib里放了mysql-connector-java-5.1了
但是不行

------解决方案--------------------
好久没有这样配置过数据源了。楼主可以参考一下:http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html