mysql+tomcat连接池配置

来源:互联网 发布:java版qq还能使用吗 编辑:程序博客网 时间:2024/06/06 13:14

第一步:项目的WebContent/META-INF文件夹下写一个context.xml如下:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd"><Context path="/项目名称" docBase="/项目名称" debug="5"crossContext="true" reloadable="true" cachingAllowed="true"cacheMaxSize="20480" cacheTTL="10000"><WatchedResource>WEB-INF/web.xml</WatchedResource><Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://数据库连接和端口如localhost:8080/数据库名?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"username="用户名" password="密码" maxActive="100" maxIdle="30"maxWait="10000" /></Context>

第二步:项目的WebContent/WEB-INF文件夹下写一个web.xml如下:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1"><display-name>Memezhuan</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><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></web-app>

第三步:测试:(要导入相应包)

String queryStr="select * from user";ResultSet rs=null;PreparedStatement pstmt=null;InitialContext ctx;ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql");try{    Connection con = ds.getConnection();    pstmt=connection.prepareStatement(queryStr);    rs=pstmt.executeQuery();    if(rs.next()){        //你要干什么坏事就自己写吧    }}catch(SQLException e){    e.printStackTrace();    }finally{    close();    }
0 0