tomcat数据库连接池配置方法

通过数据库连接池管理数据库连接、释放,使数据库操作性能得到提升,提高系统资源使用效率。

这里介绍一下采用tomcat统一管理连接池配置(Tomcat7)

1 在tomcat的conf下的context.xml加入如下配置:

    <!--配置oracle数据库的连接池-->
    <Resource name="jdbc/oracle"
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="100"
        maxIdle="30"
        maxWait="10000"
        username="scott"
        password="tiger"
        driverClassName="oracle.jdbc.dirver.OracleDriver"
        url="jdbc:oracle:thin:@127.0.0.1:1521:news" />

    <!--配置mysql数据库的连接池, 
        需要做的额外步骤是将mysql的Java驱动类放到tomcat的lib目录下        
        maxIdle 连接池中最多可空闲maxIdle个连接 
        minIdle 连接池中最少空闲maxIdle个连接 
        initialSize 初始化连接数目 
        maxWait 连接池中连接用完时,新的请求等待时间,毫秒 
        username 数据库用户名
        password 数据库密码
        -->
    <Resource name="jdbc/mysql" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="root" 
        password="root" 
        maxIdle="30" 
        maxWait="10000" 
        maxActive="100"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://127.0.0.1:3306/news" />

</Context>

2 在应用的web.xml下加入如下代码:

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

3  创建连接(java:comp/enc是固定用法)

private Connection getConnection(){
		Connection con = null;
		try {
			Context context=new InitialContext();
			DataSource data = (DataSource) context.lookup("java:comp/env/jdbc/mysql");
			con=data.getConnection();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
		
	}

猜你喜欢

转载自blog.csdn.net/qq_40693828/article/details/81051323