在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();
}