您的位置:首页 > 运维架构 > Tomcat

快速配置tomcat连接池(mysql)

2009-03-25 01:19 309 查看
配置数据库连接池(//均为注释,不应出现在实际代码中)

注意,最好将mysql-connector-java-3.1.8-bin.jar放在tomcat的common包里,这样它用起来会更简便些。

在Tomcat 5.5/conf/server.xml中

// <GlobalNamingResources>标签内添加

<Resource
name="jdbc/test"
type="javax.sql.DataSource"
password="" //数据库密码
driverClassName="org.gjt.mm.mysql.Driver" //数据库驱动
maxIdle="2"
maxWait="200"
username="root" //数据库用户名
url="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull"
maxActive="4"/>

//<Host>标签源代码
<Host appBase="webapps" name="localhost">
<Context
crossContext="true"
docBase="D:/workspace/test/WebRoot" //本地WebRoot地址
path="/test" //虚拟地址
reloadable="true">
<Resource
auth="Container"
name="jdbc/test"
type="javax.sql.DataSource"
password=""
driverClassName="org.gjt.mm.mysql.Driver"
maxIdle="10"
maxWait="-1"
username="root"
url="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull"
maxActive="20"/>
</Context>
</Host>

快速配置服务器目录与tomcat连接池完毕~!经过测试在localhost中建立xml文件定义<Context>和在<Host>中定义可以达成一样的效果。

======================================

还有一点需要注意。下面是引用别的文章

修改web.xml

打开%TOMCAT_HOME%/conf/web.xml或yourwebapp/web-inf/web.xml,添加以下内容:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
注意res-ref-name填写的内容要与在上文提到的JNDI Name名称一致。

到这里,配置工作就基本完成了!

=================

引用JNDI时用"java:comp/env/jdbc/mysql";
建立文件测试 test.jsp:
<%@page contentType="text/html;charset=utf-8" %>
<%@page import="java.sql.*" %>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<html>
<head>
<title>Tomcat连接池测试</title>
</head>
<body>
<%
Context ctx=new InitialContext();
Connection conn=null;
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
conn=ds.getConnection();
Statement stmt=conn.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from testexample");
while(rs.next()){
out.println(rs.getInt(1));
out.println(rs.getString(2));
out.println(rs.getString(3));
}
out.println("数据库操作成功!");
rs.close();
stmt.close();
conn.close();

%>
</body>
</html>

http://localhost:8080/test即可运行WebRoot。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: