Tomcat连接池配置
Tomcat 6+MySQL
数据库 pool.sql
DROP TABLE IF EXISTS `pool`; CREATE TABLE `pool` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `number` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; INSERT INTO `pool` VALUES (1,'06370101','aaaa'); INSERT INTO `pool` VALUES (2,'06370102','bbbb'); INSERT INTO `pool` VALUES (3,'06370103','cccc'); INSERT INTO `pool` VALUES (4,'06370104','dddd'); INSERT INTO `pool` VALUES (5,'06370105','eeee'); INSERT INTO `pool` VALUES (6,'06370106','ffff'); INSERT INTO `pool` VALUES (7,'06370107','gggg'); |
一 配置context.xml(Tomcat 6.0/conf/context.xml)
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/test" /> |
注:用户名,密码,数据库名称根据自己的修改
二 将MySQL数据库的jar驱动包拷贝到Tomcat 6.0/lib/目录下
三 新建Web项目
四 修改web.xml文件(WebRoot/WEB-INF/web.xml),在<web-app> </web-app>之间添加如下配置
<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/mysql</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> |
注:<res-ref-name>中的jdbc/mysql与上面context.xml中的name="jdbc/mysql"要一致。
五 在jsp页面添加测试信息
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="javax.sql.*" %> <%@ page import="javax.naming.*" %> <html> <head> <title>Tomcat连接池配置</title> </head> <body> Tomcat连接池配置<br><hr>
<% try{ Context ctx=new InitialContext(); Context envctx=(Context) ctx.lookup("java:comp/env"); DataSource ds=(DataSource) envctx.lookup("jdbc/mysql"); //Connection conn=ds.getConnection(); Connection conn=ds.getConnection(); Statement stmt=conn.createStatement(); String sql="select * from pool"; ResultSet rs=stmt.executeQuery(sql); %> <table border=""> <% while(rs.next()){ %> <tr> <td><%=rs.getString("number") %></td> <td><%=rs.getString("name") %></td> </tr> <% } %> </table> <% }catch(Exception e){ e.printStackTrace(); } %>
</body> </html> |
如有错误,请联系QQ:244077575