mysql+tomcat连接池配置

第一步:项目的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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值