局部连接池配置
1.默认使用dbcp, 可以在tomcat的目录lib下面发现tomcat-dbcp.jar
在conf/server.xml中的Host节点之间添加
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" username="root" password="xinxin"
driverClass="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/java?autoReconnect=true"
/>
然后使用eclipse新建一个Dynamic Web Project ,在WebContent 目录下面新建一个index.jsp 文件
打开web.xml文件,添加
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
index.jsp 内容为
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>This is a deployment test project</title>
</head>
<body>
<sql:query var="rs" dataSource="jdbc/TestDB">
SELECT id,name,loc,detail FROM javacasestudy
</sql:query>
<c:forEach var="row" items="${rs.rows}">
ID ${row.id}<br/>
NAME ${row.name}<br/>
LOC ${row.loc }<br/>
DETAIL ${row.detail }<br/>
</c:forEach>
<%
Context ctx=new InitialContext();
DataSource ds=(DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");
Connection conn=ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from javacasestudy");
while(rs.next()){
out.println(rs.getInt("id"));
out.println(rs.getString("name"));
out.println(rs.getString("loc"));
out.println(rs.getString("detail"));
}
%>
</body>
</html>
附录:
c3p0连接池配置
<Context path="/test" docBase="/home/jemy/Workspace/Test/WebContent" reloadable="true" debug="0">
<!--<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" username="root" password="xinxin"
driverClass="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/java?autoReconnect=true"
/>
-->
<Resource auth="Container"
driverClass="com.mysql.jdbc.Driver"
maxPoolSize="50" minPoolSize="2" acquireIncrement="2"
name="jdbc/TestDB" user="root" password="xinxin"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/java" />
</Context>
与上面的配置相比,属性的名称有所不同。需要c3p0 jar的包放置于tomcat/lib下面