Tomcat配置数据库连接池

内容概要: Tomcat提供数据库连接池管理功能,只需要在配置文件,用户可以在代码里面直接使用。

方法一: apache-tomcat/conf/context.xml中配置

首先配置context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Resource name="MysqlData"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="zhangjie"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/QQSpider"
/>
</context>

第二步,在应用中配置WEB-INF/web.xml(也可以不配置)

1
2
3
4
5
6
7
8
9
<web-app>
<!--MySQL数据库JNDI数据源引用 -->
<!-- resource-ref>
<description>MysqlData</description>
<res-ref-name>MysqlData</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref-->
</web-app>

第三步,java代码中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DBconnection
{

public static Connection getConnection() throws NamingException, SQLException
{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");// 固定,不需要修改

DataSource ds = (DataSource) envContext.lookup("MysqlData");
return ds.getConnection();


}


}


方法二: apache-tomcat/conf/server.xml为主,和context.xml一起配置

第一步,配置server.xml,在之间加入以下配置:

1
2
3
4
5
6
7
8
9
10
11
12
<GlobalNamingResources>
<Resource name="MysqlData" auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="zhangjie"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/QQSpider"
/>
</GlobalNamingResources>

第二步,配置context.xml,在中间加入以下内容

1
2
3
<context>
<ResourceLink name="MysqlData" global="MysqlData" type="javax.sql.DataSource"/>
</context>

第三步,在web应用中配置web.xml(可选,方法跟方法一内容中相同)


方法三: 直接在web应用中配置

在Web项目中的META-INF目录下新建一个文件context.xml,加入以下配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<Context privileged="true">
<Resource name="MysqlData"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="zhangjie"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/QQSpider"
/>

</Context>

方法四