1 建立数据库
mysql: 3306 test student (id,name)
2 myeclipse 生成WebProject "TestTomcatDBCP"
class path 加入3个包commond-dbcp pool collections
3 写 JAVA类
封装 获取Connection的函数
package zms.roya.dbcp;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Test1 {
public static Connection getConnection() {
try {
Context initContext = new InitialContext();
if (initContext == null)
throw new Exception("没有连接");
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/zms");
if (ds != null) {
Connection conn = ds.getConnection();
if (conn != null) {
return conn;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3 在 appweb 的 webroot/web-inf /web.xml
的根节点下增加
<resource-ref>
<description>mysql</description>
<res-ref-name>jdbc/zms</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4 在webroot/meta-inf/ 增加context.xml
<Context docBase="TestTomcatDBCP" path="/TestTomcatDBCP"
reloadable="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/zms" auth="Container"
type="javax.sql.DataSource" maxActive="100" maxIdle="30"
maxWait="10000" username="root" password="royasoft"
driverClassName= "com.mysql.jdbc.Driver"
<!--注意 这里的URL写法,和java类文件里的URL稍微有差别,characterEncoding前面的分号,开始没注意 调试了很久 -->
url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
</Context>
5 写JSP
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="zms.roya.dbcp.*"%>
<html>
<head>
</head>
<body>
<%
Connection conn=Test1.getConnection();
Statement st;
ResultSet rs;
try {
st = conn.createStatement();
rs=st.executeQuery("select * from student");
while(rs.next())
{
out.println(rs.getString(1)+"------"+rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
%>
</body>
</html>
6 发布 测试OK