我正在学习如何使用 Servlet api 并尝试开发我的第一个 Web 应用程序。而且我的 JDBC 连接有问题。我了解如何连接到我的数据库,但我想从连接池中获取连接。我不明白如何使用它。你能给我建议或链接到示例应用程序,看看它是如何工作的吗?
问问题
154 次
1 回答
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();
于 2018-07-16T19:08:42.307 回答