分类: Java
2005-02-23 09:54:28
链接地址:
实现代码:
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed 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
*
*
*
* 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 javax.sql.DataSource;
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 setupDataSource
// method. In normal use, your classes interact
// only with the standard JDBC API
//
import org.apache.commons.dbcp.BasicDataSource;
//
// Here's a simple example of how to use the BasicDataSource.
// In this example, we'll construct the BasicDataSource manually,
// but you could also configure it using an external conifguration file.
//
//
// Note that this example is very similiar to the PoolingDriver
// example.
//
// To compile this example, you'll want:
// * commons-pool.jar
// * commons-dbcp.jar
// * j2ee.jar (for the javax.sql classes)
// in your classpath.
//
// To run this example, you'll want:
// * commons-collections.jar
// * commons-pool.jar
// * commons-dbcp.jar
// * j2ee.jar (for the javax.sql classes)
// * 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-collections.jar:commons-pool.jar:commons-dbcp.jar:j2ee.jar:oracle-jdbc.jar:.
// ManualPoolingDataSourceExample
// "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid"
// "SELECT * FROM DUAL"
//
public class BasicDataSourceExample {
public static void main(String[] args) {
// First we set up the BasicDataSource.
// 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 data source.");
DataSource dataSource = setupDataSource(args[0]);
System.out.println("Done.");
//
// Now, we can use JDBC DataSource as we normally would.
//
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
System.out.println("Creating connection.");
conn = dataSource.getConnection();
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) { }
}
}
public static DataSource setupDataSource(String connectURI) {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUsername("scott");
ds.setPassword("tiger");
ds.setUrl(connectURI);
return ds;
}
public static void printDataSourceStats(DataSource ds) throws SQLException {
BasicDataSource bds = (BasicDataSource) ds;
System.out.println("NumActive: " + bds.getNumActive());
System.out.println("NumIdle: " + bds.getNumIdle());
}
public static void shutdownDataSource(DataSource ds) throws SQLException {
BasicDataSource bds = (BasicDataSource) ds;
bds.close();
}
}
参数:
Parameter | Description |
---|---|
username | The connection username to be passed to our JDBC driver to establish a connection. |
password | The connection password to be passed to our JDBC driver to establish a connection. |
url | The connection URL to be passed to our JDBC driver to establish a connection. |
driverClassName | The fully qualified Java class name of the JDBC driver to be used. |
connectionProperties | The connection properties that will be sent to our JDBC driver when establishing new connections. Format of the string must be [propertyName=property;]* NOTE - The "user" and "password" properties will be passed explicitly, so they do not need to be included here. |
Parameter | Default | Description |
---|---|---|
defaultAutoCommit | true | The default auto-commit state of connections created by this pool. |
defaultReadOnly | driver default | The default read-only state of connections created by this pool. If not set then the setReadOnly method will not be called. (Some drivers don't support read only mode, ex: Informix) |
defaultTransactionIsolation | driver default | The default TransactionIsolation state of connections created by this pool. One of the following: (see )
|
defaultCatalog | The default catalog of connections created by this pool. |
Parameter | Default | Description |
---|---|---|
initialSize | 0 | The initial number of connections that are created when the pool is started. Since: 1.2 |
maxActive | 8 | The maximum number of active connections that can be allocated from this pool at the same time, or zero for no limit. |
maxIdle | 8 | The maximum number of active connections that can remain idle in the pool, without extra ones being released, or zero for no limit. |
minIdle | 0 | The minimum number of active connections that can remain idle in the pool, without extra ones being created, or zero to create none. |
maxWait | indefinitely | The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely. |
Parameter | Default | Description |
---|---|---|
validationQuery | The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row. | |
testOnBorrow | true | The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. |
testOnReturn | false | The indication of whether objects will be validated before being returned to the pool. |
testWhileIdle | false | The indication of whether objects will be validated by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool. |
timeBetweenEvictionRunsMillis | -1 | The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run. |
numTestsPerEvictionRun | 3 | The number of objects to examine during each run of the idle object evictor thread (if any). |
minEvictableIdleTimeMillis | 1000 * 60 * 30 | The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any). |
Parameter | Default | Description |
---|---|---|
poolPreparedStatements | false | Enable prepared statement pooling for this pool. |
maxOpenPreparedStatements | unlimited | The maximum number of open statements that can be allocated from the statement pool at the same time, or zero for no limit. |
This component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled:
NOTE - Make sure your connection has some resources left for the other statements.
Parameter | Default | Description |
---|---|---|
accessToUnderlyingConnectionAllowed | false | Controls if the PoolGuard allows access to the underlying connection. |
When allowed you can access the underlying connection using the following construct:
Connection conn = ds.getConnection(); Connection dconn = ((DelegatingConnection) conn).getInnermostDelegate(); ... conn.close()
Default is false, it is a potential dangerous operation and misbehaving programs can do harmfull things. (closing the underlying or continue using it when the guarded connection is already closed) Be carefull and only use when you need direct access to driver specific extentions.
NOTE: Do not close the underlying connection, only the original one.
Parameter | Default | Description |
---|---|---|
removeAbandoned | false | Flag to remove abandoned connections if they exceed the removeAbandonedTimout. If set to true a connection is considered abandoned and eligible for removal if it has been idle longer than the removeAbandonedTimeout. Setting this to true can recover db connections from poorly written applications which fail to close a connection. |
removeAbandonedTimeout | 300 | Timeout in seconds before an abandoned connection can be removed. |
logAbandoned | false | Flag to log stack traces for application code which abandoned a Statement or Connection. Logging of abandoned Statements and Connections adds overhead for every Connection open or new Statement because a stack trace has to be generated. |
If you have enabled "removeAbandoned" then it is possible that a connection is reclaimed by the pool because it is considered to be abandoned. This mechanism is triggered when (getNumIdle() < 2) and (getNumActive() > getMaxActive() - 3) For example maxActive=20 and 18 active connections and 1 idle connection would trigger the "removeAbandoned". But only the active connections that aren't used for more then "removeAbandonedTimeout" seconds are removed, default (300 sec). Traversing a resultset doesn't count as being used.