将JDBC插件放入Tomcat的lib目录中
修改Tomcat的2个配置文件
(1)修改context.xml
在Context的结束标签之前加入:
<Resource
name="jdbc/t1"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/t1"
/>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
我的database名是:t1
table名是:bnutalk
用户名是root
密码是123456
你只要修改对应的地方就可以了,添加后效果如下:
(2)修改web.xml
在webapp的结束标签之前加入:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/t1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
- 1
- 2
- 3
- 4
- 5
- 6
将t1改成你的数据库名就行了。
测试是否配置成功
(1)新建一个Serve和一个Dynamic Web Project项目
(2)new一个jsp文件,名字任意
index.jsp代码如下:
<%@ page language="java" contentType="text/html"
pageEncoding="GBK" import="java.sql.*,javax.sql.*,javax.naming.*"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Context ctx=new InitialContext();
Connection conn=null;
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/t1");
conn=ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select id,age from bnutalk");
while(rs.next()){
System.out.println(rs.getInt("id")+","+rs.getInt("age"));
}
rs.close();
stmt.close();
conn.close();
%>
</body>
</html>