打开%TOMCAT_HOME%/conf/server.xml,在</Host>节点前加入以下代码:
- <Context path="/connectionPool" docBase="connectionPool" debug="0"
- reloadable="true" crossContext="true">
- <Resource name="jdbc/query"
- auth="Container" type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- maxIdle="20" maxWait="5000" username="root" password="javajsp"
- url="jdbc:mysql://localhost:3306/matchinfo"
- maxActive="8" removeAbandoned="true"
- removeAbandonedTimeout="60" logAbandoned="true"/>
- </Context>
在相应的web app 的web.xml,加入以下配置.
- <resource-ref>
- <res-ref-name>jdbc/query</res-ref-name>
- <res-type>javax.sql.DataSource</res-type>
- <res-auth>Container</res-auth>
- </resource-ref>
可以使用如下代码,得到数据库连接:
- package org.james.test;
- import java.sql.Connection;
- import java.sql.SQLException;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import javax.sql.DataSource;
- public class ConnectionPool {
- public Connection getConnection(){
- Connection conn = null;
- try {
- Context initCtx = new InitialContext();
- Context envCtx = (Context) initCtx.lookup("java:comp/env");
- DataSource ds = (DataSource)envCtx.lookup("jdbc/query");
- conn = ds.getConnection();
- } catch (NamingException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return conn;
- }
- }
若在测试时,抛出未找到mysql jdbc驱动的异常.可在 打开%TOMCAT_HOME%/lib 目录下手动加入mysql驱动jar.