/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbcp;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
//
// Here are the dbcp-specific classes.
// Note that they are only used in the setupDriver
// method. In normal use, your classes interact
// only with the standard JDBC API
//
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
//
// Here's a simple example of how to use the PoolingDriver.
// In this example, we'll construct the PoolingDriver manually,
// just to show how the pieces fit together, but you could also
// configure it using an external conifguration file in
// JOCL format (and eventually Digester).
//
//
// To compile this example, you'll want:
// * commons-pool-1.5.4.jar
// * commons-dbcp-1.2.2.jar
// in your classpath.
//
// To run this example, you'll want:
// * commons-collections.jar
// * commons-pool-1.5.4.jar
// * commons-dbcp-1.2.2.jar
// * the classes for your (underlying) JDBC driver
// in your classpath.
//
// Invoke the class using two arguments:
// * the connect string for your underlying JDBC driver
// * the query you'd like to execute
// You'll also want to ensure your underlying JDBC driver
// is registered. You can use the "jdbc.drivers"
// property to do this.
//
// For example:
// java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver \
// -classpath commons-pool-1.5.3.jar:commons-dbcp-1.2.2.jar:oracle-jdbc.jar:. \
// ManualPoolingDriverExample \
// "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid" \
// "SELECT * FROM DUAL"
//
public class ManualPoolingDriverExample {
public static void main(String[] args) {
//
// First we load the underlying JDBC driver.
// You need this if you don't use the jdbc.drivers
// system property.
//
System.out.println("Loading underlying JDBC driver.");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Done.");
//
// Then we set up and register the PoolingDriver.
// Normally this would be handled auto-magically by
// an external configuration, but in this example we'll
// do it manually.
//
System.out.println("Setting up driver.");
try {
setupDriver(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done.");
//
// Now, we can use JDBC as we normally would.
// Using the connect string
// jdbc:apache:commons:dbcp:example
// The general form being:
// jdbc:apache:commons:dbcp:<name-of-pool>
//
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
System.out.println("Creating connection.");
conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example");
System.out.println("Creating statement.");
stmt = conn.createStatement();
System.out.println("Executing statement.");
rset = stmt.executeQuery(args[1]);
System.out.println("Results:");
int numcols = rset.getMetaData().getColumnCount();
while(rset.next()) {
for(int i=1;i<=numcols;i++) {
System.out.print("\t" + rset.getString(i));
}
System.out.println("");
}
} catch(SQLException e) {
e.printStackTrace();
} finally {
try { if (rset != null) rset.close(); } catch(Exception e) { }
try { if (stmt != null) stmt.close(); } catch(Exception e) { }
try { if (conn != null) conn.close(); } catch(Exception e) { }
}
// Display some pool statistics
try {
printDriverStats();
} catch (Exception e) {
e.printStackTrace();
}
// closes the pool
try {
shutdownDriver();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setupDriver(String connectURI) throws Exception {
//
// First, we'll need a ObjectPool that serves as the
// actual pool of connections.
//
// We'll use a GenericObjectPool instance, although
// any ObjectPool implementation will suffice.
//
ObjectPool connectionPool = new GenericObjectPool(null);
//
// Next, we'll create a ConnectionFactory that the
// pool will use to create Connections.
// We'll use the DriverManagerConnectionFactory,
// using the connect string passed in the command line
// arguments.
//
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null);
//
// Now we'll create the PoolableConnectionFactory, which wraps
// the "real" Connections created by the ConnectionFactory with
// the classes that implement the pooling functionality.
//
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
//
// Finally, we create the PoolingDriver itself...
//
Class.forName("org.apache.commons.dbcp.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
//
// ...and register our pool with it.
//
driver.registerPool("example",connectionPool);
//
// Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
// to access our pool of Connections.
//
}
public static void printDriverStats() throws Exception {
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
ObjectPool connectionPool = driver.getConnectionPool("example");
System.out.println("NumActive: " + connectionPool.getNumActive());
System.out.println("NumIdle: " + connectionPool.getNumIdle());
}
public static void shutdownDriver() throws Exception {
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.closePool("example");
}
}
分享到:
相关推荐
这篇“DBCP 数据库连接池JNDI连接 学习笔记”主要探讨了如何结合JNDI(Java Naming and Directory Interface)来使用DBCP进行数据库连接管理。JNDI提供了一种标准的方式来查找和绑定资源,如数据源,在企业级应用中...
**JDBC学习笔记** 在Java开发中,JDBC(Java Database Connectivity)是连接数据库的关键技术。它是Java API,允许Java程序与各种类型的数据库进行交互。本笔记将深入探讨JDBC的核心概念、工作原理以及实际应用。 ...
### 传智播客JDBC学习笔记精要 #### JDBC简述与连接 JDBC(Java Database Connectivity)是Java中用来规范客户端程序如何访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。在传智播客的JDBC...
### Spring学习笔记知识点详解 #### 一、Spring框架概述 **Spring** 是一个开源的、分层的企业级应用开发框架,旨在简化Java EE应用程序的开发。它的主要目标是提高开发效率,减少耦合度,并提供一种更为简洁的...
Java数据库学习笔记主要聚焦在Java如何与数据库进行交互,尤其是通过Java Database Connectivity(JDBC)API。JDBC是Java平台中的一个标准接口,它允许Java应用程序连接到各种类型的数据库,无论是关系型数据库还是...
【张龙S2SH学习笔记(经典)】是基于圣思园张龙的视频教程整理出的学习资料,主要涵盖了Struts2、Spring和Hibernate这三大框架的整合使用,也就是我们常说的SSH(Spring、Struts2、Hibernate)框架集成。SSH框架在...
在描述中提到的“Spring2学习笔记帮你完善管理SSH”,这里的SSH通常是指Struts、Spring和Hibernate的组合,这是一种经典的Java Web开发架构。 首先,我们来详细讲解Spring 2中的核心概念: 1. **依赖注入...
【Spring 2.5 学习笔记】 在深入学习Spring 2.5的过程中,我们可以了解到一系列关键的概念和技术。首先,面向抽象编程是Spring的核心理念之一,它鼓励开发者编写可重用且松散耦合的代码,通过接口而非具体实现进行...
在本篇JDBC学习笔记中,我们将深入探讨JDBC的基础知识、核心概念以及实际应用。 一、JDBC基础 1. JDBC驱动程序:JDBC驱动是连接Java应用程序和数据库之间的桥梁。根据实现方式,JDBC驱动分为四种类型:类型1(JDBC...
本学习笔记将深入探讨这两个技术的基础知识,以帮助初学者掌握它们的基本概念和应用。** ### JSP基础 1. **JSP概述**:JSP是一种基于Java的技术,它允许在服务器端生成HTML,使得开发者可以在网页中嵌入Java代码,...
**JDBC实战教程-尚硅谷学习笔记 2022版** Java Database Connectivity(JDBC)是Java语言中用于与数据库交互的一种接口,由Sun Microsystems公司开发并纳入Java标准库,使得Java程序员能够以标准化的方式来访问各种...
这篇“连接池学习笔记”涵盖了关于连接池的基本概念、工作原理以及常见的数据库连接池实现,旨在帮助读者深入理解这一工具。以下是对该主题的详细阐述: 一、连接池的概念 连接池是一种对象池设计模式的具体应用,...
本篇JDBC学习笔记将深入探讨JDBC的核心概念、操作步骤以及最佳实践。 **一、JDBC基本概念** 1. **驱动程序**:JDBC驱动程序是Java应用程序与数据库之间的桥梁,分为四种类型:JDBC-ODBC桥接驱动、本地API驱动、...
**超经典的JDBC学习笔记** Java Database Connectivity (JDBC) 是Java编程语言中用来规范客户端程序如何访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。本笔记将深入细致地探讨JDBC的核心概念...
**使用DBCP(Apache Commons DBCP)** DBCP是Apache Commons Pool的一个子项目,提供了对数据库连接池的支持。在Spring中,可以使用`BasicDataSource`作为数据源,它同样是在XML配置文件中定义: ```xml ...
【JDBC学习笔记详解】 JDBC(Java Database Connectivity)是Java语言中用来规范客户端程序如何访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC是Java程序员与各种数据库之间通信的桥梁,...
**JDBC学习笔记** JDBC(Java Database Connectivity)是Java编程语言中用于规范客户端程序如何访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC是Java平台的标准,使得开发者能够编写与...