(备忘)Eclipse下配置tomcat连接池连接mysql数据库

过段时间可能会用到,今天稍微研究了一下,留在这里备忘.

Eclipse用了Eclipse Java EE IDE for Web Developers.版本.http://www.eclipse.org/downloads/这里可以下到

Tomcat用了7.0版本,在Eclipse中下载的.创建Dynamic Web Project项目时就会看到要求你下载Tomcat的提示

mysql使用了5.6.10版本.http://dev.mysql.com/downloads/installer/这里可以下到


配置的时候需要修改tomcat两个配置文件

1:context.xml

在<Context></Context>中加入

<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" 
		maxActive="50" maxIdle="10" maxWait="5000" username="root" password="root" 
		diverClassName="org.git.mm.mysql.Driver" url="jdbc:mysql://localhost:3306/world"/>
url中的world是你要连接的Schema名称

2:web.xml

在<web-app></web-app>中加入

<resource-ref>   
        <description>DB Connection</description>   
        <res-ref-name>jdbc/mysql</res-ref-name>   
        <res-type>javax.sql.DataSource</res-type>   
        <res-auth>Container</res-auth>   
    </resource-ref>
要注意的是context.xml中的name值与web.xml的res-ref-name名称要相同.

3:代码中添加

DataSource ds = null;
try{
	InitialContext ctx = new InitialContext();
	ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
	Connection conn = ds.getConnection();
	Statement stmt = conn.createStatement();
	String sql = "select * from city";
	ResultSet rs = stmt.executeQuery(sql); 
	while(rs.next()){
		response.getOutputStream().print("name: "+rs.getString(1));
	}
}
catch(Exception ex)
{
	ex.printStackTrace();
}
代码里需要注意的是DataSource一定要用web.xml中res-type的DataSource.

我起初就是把web.xml中的res-type值设置为javax.sql.DataSource,代码里自动引入了sun.jdbc.odbc.ee.DataSource.

结果造成org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to sun.jdbc.odbc.ee.DataSource异常,google了一番后,明白了是DataSource这里出了问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值