Tomcat6.x DataSource的配备与使用
为什么上一篇连接池说的那么草,就是因为理解原理即可,自己实现一个线程安全性能可以的连接池是有一定难度的,我们在实际开发过程中,一般是用DataSource就可以了。
可以说,DataSource就是Tomcat提供给我们使用已实现的连接池的一个接口。
在Tomcat6.0中的配置如下:
在webapp/工程名/META-INF/
中建立Context.xml
内容:
<Context>
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="1234" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test?autoReconnect=true"/>
</Context>
在web.xml中加入:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/bookstore_db</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
使用时,连接创建过程:
javax.naming.Context
Context context = new InitialConetext();
DataSource ds = conext.lookup("java:/comp/env/jdbc/bookstore_db");
ds.getConnection();
其实,具体的过程,在tomcat的manager中manager-help中都有,介绍的比这儿好多了,自己看吧!
最后说一点注意,那个mysqlDriver是Tomcat用,所以:
在Tomcat6.0中使用javax.sql.DataSource时,我们必须保证工程中和Tomcat的lib中都包含Driver的驱动程序jar包,否则抛出不能加载:com.jdbc.mysql.Driver异常。