我正在学习如何使用Servlet api并尝试开发我的第一个Web应用程序。而且我对JDBC连接有问题。我了解如何连接到数据库,但是我想从连接池中获得连接。我不明白如何使用它。您能否给我建议或链接到示例应用程序以查看其工作原理?
答案 0 :(得分:0)
GenericObjectPool类可用于创建任意对象池。您可以如下创建池。
public DataSource setUpPool() throws Exception {
Class.forName(JDBC_DRIVER);
// Creates an Instance of GenericObjectPool That Holds Our Pool of Connections Object!
gPool = new GenericObjectPool();
gPool.setMaxActive(5);
// Creates a ConnectionFactory Object Which Will Be Use by the Pool to Create the Connection Object!
ConnectionFactory cf = new DriverManagerConnectionFactory(JDBC_DB_URL, JDBC_USER, JDBC_PASS);
// Creates a PoolableConnectionFactory That Will Wraps the Connection Object Created by the ConnectionFactory to Add Object Pooling Functionality!
PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, null, null, false, true);
return new PoolingDataSource(gPool);
}
使用上述方法从池中获取连接:
ConnectionPool jdbcObj = new ConnectionPool();
Connection connObj = null;
DataSource dataSource = jdbcObj.setUpPool();
connObj = dataSource.getConnection();