最近研究了一下tomcat数据库连接池的配置,花了很长时间,走了不少弯路,总是冒出一些莫名其妙的异常,现将配置简略地概述一下。我采用的数据库是mysql。
1. 将数据库连接驱动包mysql-connector-java-5.0.2-beta-bin.jar放到tomcat安装目录中的lib中。
2. 在tomcat的安装目录下的server.xml中配置数据源。在server.xml文件里的<GlobalNamingResources></GlobalNamingResources>节点下增加如下配置:
<Resource name="jdbc/DBPool"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/haozhierp"
username="root"
password="root"
maxIdle="2"
maxActive="4"/>
属性说明:name,数据源名称,通常取”jdbc/XXX”的格式;
type,”javax.sql.DataSource”;
username,数据库用户名;
password,数据库用户密码;
driveClassName,数据库驱动;
maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
MaxActive,连接池的最大数据库连接数。设为0表示无限制。
maxWait,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
3.在tomcat安装目录下的context.xml中配置数据源链接。在context.xml文件里的<Context></Context>节点下添加如下配置:
<ResourceLink name="jdbc/DBPool"
type="javax.sql.DataSource"
global="jdbc/DBPool"
/>
属性说明:
name,同第2步属性name值;
type,同样取”javax.sql.DataSource”;
global,同name值。
4.在你的web工程的web.xml里配置数据源参考,具体代码如下:
<resource-ref>
<res-ref-name>jdbc/DBPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
子节点说明:
res-ref-name,参考数据源名字,同上一步的属性name;
res-type,资源类型,”javax.sql.DataSource”;
res-auth,”Container”;
res-sharing-scope,”Shareable”;
至此,数据库连接池配置已经完成。以下十个测试的小例子:
首先,创建一个数据库连接池类:
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 DBPool {
public static Connection getConnection() throws NamingException, SQLException{
Context con = null;
con = (Context) new InitialContext().lookup("java:comp/env");
DataSource pool = (DataSource) con.lookup("jdbc/DBPool");
if(pool == null){
System.out.println("DB pool is not founded!");
}
return pool.getConnection();
}
}
接着,创建一个jsp页面index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="jndi.DBPool"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
This is my JSP page.
<br>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = DBPool.getConnection();
stmt = conn.createStatement();
String sql = "select * from basic_unit";
rs = stmt.executeQuery(sql);
while(rs.next()){
%>
<% out.println("Id=" + rs.getString("Unit_Id") + ",Name=" + rs.getString("Unit_Name")); %>
<% }
}catch(Exception e){
e.printStackTrace();
}finally{
rs.close();
stmt.close();
conn.close();
}
%>
</body>
</html>
现在,就可以运行了。