时间:2021-07-01 10:21:17 帮助过:7人阅读
我的database名是:t1
table名是:bnutalk
用户名是root
密码是123456
你只要修改对应的地方就可以了,添加后效果如下:
在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>
将t1改成你的数据库名就行了。
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>
Serverlet代码如下:
package com.imooc.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServlet
*/
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
我的t1数据库中的bnutalk表的内容是:
下面来看看输出的内容是否和数据库中的吻合:
右键web项目->run on server
输出结果如下:
ok,到此为止,Tomcat的数据库连接池就配置成功了。
Tomcat数据库连接池配置
标签: