您的位置:首页 > 编程语言 > Java开发

Java 用DBCP连接数据库。

2016-03-02 00:00 671 查看
摘要: 事实上如果你用DBCP连接数据库,配置连接池之类的,因为账户和密码在连接池已经设置好了,事实上不需要再去设置了,但是很奇怪,项目上面有个文件又设置了一遍。

DBCP使用说明

http://commons.apache.org/proper/commons-pool/api-2.4.2/org/apache/commons/pool2/PooledObjectFactory.html?is-external=true

代码实例可以参考

http://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.dbcp2.PoolableConnectionFactory

/*
* 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.
*/

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 { rset.close(); } catch(Exception e) { }
try { stmt.close(); } catch(Exception e) { }
try { 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");
}
}


JOCL 例子

<!--
Sample JOCL configuration file for JOCLPoolingDriverExample.java.

It's not pretty, but it works.  It will be replaced by Digester-based
configuration as soon as it's available.

See the JavaDocs for org.apache.commons.jocl.JOCLContentHandler for
documentation on JOCL in general. The gist of it is an that it provides
an XML description of a constructor to be invoked.

See the JavaDocs for PoolableConnectionFactory et al for details
on the object we are constructing. The inline comments may help as well.

To use this with the JOCLPoolingDriverExample, make a copy of this
file called it "poolingDriverExample.jocl", set the connection string below
(search for "CHANGE ME"), and make sure the poolingDriverExample.jocl file
is available in your classpath. (See JOCLPoolingDriverExample.java.)
-->

<!--
The PoolingDriver expects PoolableConnectionFactory to be the root of the JOCL document.
-->
<object class="org.apache.commons.dbcp.PoolableConnectionFactory" xmlns="http://apache.org/xml/xmlns/jakarta/commons/jocl">
<!--
The first argument to PoolableConnectionFactory is a ConnectionFactory.
We'll use a DriverManagerConnectionFactory, passing in the appropriate
connect string for the underlying driver.
-->
<object class="org.apache.commons.dbcp.DriverManagerConnectionFactory">
<string value="jdbc:oracle:thin:scott/tiger@myhost:1521:mysid"/> <!-- CHANGE ME TO THE CONNECT STRING FOR YOUR DRIVER -->
<object class="java.util.Properties" null="true"/>
</object>
<!--
The next argument is the pool to use.  We'll use a StackObjectPool,
although any implementation of ObjectPool should suffice.
-->
<object class="org.apache.commons.pool.impl.StackObjectPool"/>
<!--
The next argument is the KeyedObjectPoolFactory to use to create pools
for storing PreparedStatements.  This functionality is optional, we'll
just use null.
-->
<object class="org.apache.commons.pool.KeyedObjectPoolFactory" null="true"/>
<!--
The next argument is the query to use to validate that a Connection is
still up and running.  It should return at least one row.
This functionality is optional. We'll just set it to null.
-->
<string null="true"/>
<!-- The default "read only" value for Connections. -->
<boolean value="false"/>
<!-- The default "auto commit" value for Connections. -->
<boolean value="true"/>
</object>

jocl 例子,设置最小连接数可以使用 max-idle

http://commons.apache.org/proper/commons-dbcp/api-1.4/org/apache/commons/dbcp/package-summary.html

For example, suppose you create a pool named "/eg" from a JOCL document. The "connect string" for this pool will be "jdbc:apache:commons:dbcp:/eg". To do this, you'll need a create a resource (just a file in your classpath) containing a JOCL description of the pool. Specifically, this JOCL document should define a PoolableConnectionFactory from which the pool will be obtained. For example:

<object class="org.apache.commons.dbcp.PoolableConnectionFactory" xmlns="http://apache.org/xml/xmlns/jakarta/commons/jocl">
<!-- the first argument is the ConnectionFactory -->
<object class="org.apache.commons.dbcp.DriverManagerConnectionFactory">
<string value="jdbc:some:connect:string"/>
<object class="java.util.Properties" null="true"/>
</object>
<!-- the next argument is the ObjectPool -->
<object class="org.apache.commons.pool.impl.GenericObjectPool">
<object class="org.apache.commons.pool.PoolableObjectFactory" null="true"/>
<int value="10"/> <!-- max active -->
<byte value="1"/> <!-- when exhausted action, 0 = fail, 1 = block, 2 = grow -->
<long value="2000"/> <!-- max wait -->
<int value="10"/> <!-- max idle -->
<boolean value="false"/> <!-- test on borrow -->
<boolean value="false"/> <!-- test on return -->
<long value="10000"/> <!-- time between eviction runs -->
<int value="5"/> <!-- number of connections to test per eviction run -->
<long value="5000"/> <!-- min evictable idle time -->
<boolean value="true"/> <!-- test while idle -->
</object>
<!-- the next argument is the KeyedObjectPoolFactory -->
<object class="org.apache.commons.pool.impl.StackKeyedObjectPoolFactory">
<int value="5"/> <!-- max idle -->
</object>
<string value="SELECT COUNT(*) FROM DUAL"/> <!-- validation query -->
<boolean value="false"/> <!-- default read only -->
<boolean value="true"/> <!-- default auto commit -->
</object>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息