JSP连接Mysql的数据库连接池配置相关

来源:互联网 发布:图像算法工程师 知乎 编辑:程序博客网 时间:2024/05/21 20:27

先要下载好数据库连接驱动放在tomcat的lib文件夹下,在tomcat的conf目录下打开context.xml加入代码:DBPool为连接池名字,可随便取,但是要对应;student为数据库名,开发环境:  JDK+ Tomcat+Mysql+Myeclipse

<Context>
<Resource
name = "jdbc/DBPool" //指定连接池的名称
auth = "Container"
type = "javax.sql.DataSource" //指定连接池的类,它负责连接池的事务处理
password = "123456" //链接数据库的密码
driverClassName = "com.mysql.jdbc.Driver" //链接数据库使用的驱动程序
maxIdle = "2" //连接池中连接的最大空闲数
maxWait = "5000" //指定最大建立连接等待时间,如果超过此时间将发生异常
username = "root" //链接数据库的用户名
url = "jdbc:MYSQL://localhost:3306/student?characterEncoding=GB2312"//指定链接的数据库
maxActive = "4"         //连接池最大连接数

/>

<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>

然后在工程的web.xml文件中加入代码:
<resource-ref>
  <description>MySQL数据库连接池配置</description> //description为描述信息
  <res-ref-name>jdbc/DBPool</res-ref-name> //res-ref-name指定参考数据源名称
  <res-type>javax.sql.DataSource</res-type> //res-type为资源类型
  <res-auth>Container</res-auth> //res-auth为连接名
  <res-sharing-scope>Shareable</res-sharing-scope> //指定是否可以被共享
  </resource-ref>

以下是我自己的测试文件

首先要创建数据库student,接着创建student表,此表包含id(int)、name(char)、addr(char)、tel(char)共四个字段,代表学生的编号、姓名、地址、电话。

<%@page import="javax.naming.InitialContext"%><%@page import="javax.naming.Context"%><%@page import="javax.sql.DataSource"%><%@ page language="java" import="java.util.*,java.io.*,java.sql.*" pageEncoding="gb2312"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'PoolLink.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <%    DataSource pool=null;    Context env=null;    Connection con=null;    Statement st=null;    ResultSet rs=null;    try{    env=(Context)new InitialContext().lookup("java:comp/env");    pool=(DataSource)env.lookup("jdbc/DBPool");    if(pool==null)    out.println("找不到指定连接池");    con=pool.getConnection();    st=con.createStatement();    rs=st.executeQuery("select * from student");    while(rs.next()){    out.print(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+"<br>");    }    }catch(Exception e){    out.print(e.toString());}     %>  </body></html>


0 0