`
luck332
  • 浏览: 84834 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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

    博客分类:
  • java
阅读更多
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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics