tomcat配置连接池(MySQL数据库)

在TOMCAT_HOME\conf\context.xml文件的<Context>节点中加入:

<Resource
name="jdbc/sql"
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:3306/test"
/>

属性解释:

name:数据源名字 auth:权限 type:类型

maxActive:最大连接数据库连接数,设 0 为没有限制
maxIdle:最大等待连接中的数量,设 0 为没有限制
maxWait:最大等待毫秒数, 单位为 ms, 超过时间会出错误信息

在web应用的web.xml中加入

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/sql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

在项目中获取连接方法:

Context initContext=new InitialContext();
Context envContext=(Context)initContext.lookup("java:/comp/env");
DataSource ds=(DataSource)envContext.lookup("jdbc/sql");
Connection conn=ds.getConnection();
Statement st=null;
ResultSet rs=null;
st=conn.createStatement();
rs=st.executeQuery(sql);

你可能感兴趣的:(sql,tomcat,Web,mysql,jdbc)