Tomcat 的数据库连接池设置与应用

本文详细介绍如何在Tomcat服务器中配置SQL数据库连接池,包括添加数据库驱动、配置server.xml和web.xml文件、设置context.xml等步骤,并提供了一个简单的测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tomcat 的数据库连接池设置与应用
1.以SQL数据库为例,将数据库驱动程序的JAR文件放在Tomcat的 common/lib 中;从http://jakarta.apache.org/commons/dbcp/下载commons-dbcp-1.2.1.zip,将其中的commons-dbcp-1.2.1.jar放到jre/lib/ext和Tomcat 5.5/common/lib里面。
2.在Tomcat 5.5/conf/server.xml的<GlobalNamingResources>中添加:
<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="sa" password="" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test"/>
属性说明:name,数据源名称,通常取”jdbc/***”的格式;
password,数据库用户密码;
driveClassName,数据库驱动;
maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
接将被标记为不可用,然后被释放。设为0表示无限制。
MaxActive,连接池的最大数据库连接数。设为0表示无限制。
maxWait ,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
无限制。
3.在你的web应用程序的web.xml中设置数据源参考,如下:
在<web-app></web-app>节点中加入,
<resource-ref>
<description>SQL DB Connection Pool</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
子节点说明: description,描述信息;
res-ref-name,参考数据源名字,同上一步的属性name;
res-type,资源类型,”javax.sql.DataSource”;
res-auth,”Container”;
res-sharing-scope,”Shareable”;
4. 在Tomcat 5.5/webapps/test/META-INF/context.xml的<Context>中添加
在<Context></Context>节点中加入,
<ResourceLink
name='jdbc/test'
type='javax.sql.DataSource'
global='jdbc/test'/>
属性说明:name,同第2步和第3步的属性name值,和子节点res-ref-name值;
type,同样取”javax.sql.DataSource”;
global,同name值。

5.测试
重启Tomcat服务器,写一个test.jsp:
<%@ page language="java" contentType="text/html; charset=gb2312" %>
<%@ page import="javax.naming.*" %>
<%@ page import="javax.sql.*"%>
<%@ page import="java.sql.*" %>
<html>
<head>

</head>

<body>

<%
DataSource ds = null;
try{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
ds = (DataSource)envCtx.lookup("jdbc/test");
if(ds!=null){
out.println("Connection is OK!");
Connection **=*s.getConnection();
out.println("Connection is oooooo!");
if(cn!=null){
out.println("cn is Ok!");
Statement stmt = cn.createStatement();

ResultSet rst = stmt.executeQuery("select * from password");

out.println("rst is Ok!"+"<br>");
while(rst.next()){
out.println(rst.getString(1));
out.println(rst.getString(2));
out.println("<br>");
}

cn.close();
} else {
out.println("rst Fail!");
}
} else {
out.println("Fail!");
}
}catch(Exception ne){
out.println(ne);
}
%>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值