web项目中数据库连接池的建立(1)

在web项目中使用数据库连接池为了解决资源的频繁分配与连接所造成的问题。

那么,我们该怎样来使用呢?

有两种方式。

JNDI方式和非JNDI方式。

①非JNDI方式。也就是用纯java代码。

首先,我们需要到Apache的官网上下载一些东西。http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi

http://commons.apache.org/proper/commons-pool/download_pool.cgi

在这两个下载页面中下载他们的压缩包。解压后复制.jar文件到MyEclipse项目的webroot/web-info/lib中。

然后参照API文档,编写代码。

以下是API文档中的源代码。

public class Pool
{
    private static DataSource ds;

    static
    {
        DriverAdapterCPDS cpds = new DriverAdapterCPDS();
        cpds.setDriver("org.gjt.mm.mysql.Driver");
        cpds.setUrl("jdbc:mysql://localhost:3306/bookstore");
        cpds.setUser("foo");
        cpds.setPassword(null);

        SharedPoolDataSource tds = new SharedPoolDataSource();
        tds.setConnectionPoolDataSource(cpds);
        tds.setMaxActive(10);
        tds.setMaxWait(50);

        ds = tds;
    }

    public static getConnection()
    {
        return ds.getConnection();
    }  
}

This class can then be used wherever a connection is needed:

    Connection con = null;
    try
    {
        con = Pool.getConnection();
        ... 
        use the connection
        ...
    }
    finally
    {
        if (con != null)
            con.close();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值