JavaWeb的mysql的数据库连接池
1.数据库连接池的原理
数据库连接池的基本思想就是为数据库连接建立一个“存储池”。连接池是一个可以存储多个数据库连接对象的容器,当程序需要连接数据库池,可直接从连接池中获取一个连接,使用结束后再将连接还给连接池。这样一个连接可以被很多个程序共享,无需每次都与数据库交互时都与数据库进行连接与断开,提高数据库访问速度。
2.配置数据库连接池
第一步:打开Tomcat安装目录下的“conf\context.xml"配置文件,在标签<context>末端加入以下内容:
<Resource name="jdbc/product"
auth="Container"
type="javax.sql.DataSource"
maxIdle="10"
maxWaitMillis="1000"
maxTotal="10"
username="root"
password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/product" />
其中本人的Tomcat为8.0版本,所以使maxWaitMillis,maxTotal,其中的mysql为小写。
该类型适用于Tomcat8.0和8.5,其它的不知道。
如果为Tomcat6.0,将其中的maxWaitMillis和maxTotal改为maxWait,maxActive,将mysql改为MYSQL;product为数据库名称;
第二步:在项目WEB-INF目录下找到web.xml配置文件,然后打开,在标签<web-app>中加入以下内容:
<resource-ref>
<description>DBConnection</description>
<res-ref-name>jdbc/product</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
其中DBconnection为自定义,而jdbc/course是对应上面的<Resource>标签中的name属性,还javax.sql.DataSource就对应type属性的值,而最后Container对应的使auth属性的值。
第3步,将JDBC的驱动jar包放到Tomcat安装的lib文件夹里。我的使mysql5.1的jar包,如果版本过低,运行可能会有问题。
第四步:进行测试。
<%@ page language="java" import="java.util.*,java.sql.*,javax.naming.*,javax.sql.DataSource" pageEncoding="utf-8"%>
<html>
<body>
<table bgcolor = lightgrey>
<tr>
<td>商品编号</td>
<td>商品介绍</td>
</tr>
<%
InitialContext ctx;
PreparedStatement pstmt = null;
Connection conn = null;
String sql = "select product_no,Introductory from product";
ctx = new InitialContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/product");
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
out.println("使用数据连接池访问商品信息");
while(rs.next()){
%>
<tr bgcolor=cyan>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%}
%>
</table>
</body>
</html>
如果显示出此页面则说明可以运行