Chinaunix首页 | 论坛 | 博客
  • 博客访问: 774595
  • 博文数量: 160
  • 博客积分: 2516
  • 博客等级: 大尉
  • 技术积分: 1511
  • 用 户 组: 普通用户
  • 注册时间: 2004-10-24 17:58
文章分类

全部博文(160)

文章存档

2019年(2)

2018年(3)

2017年(15)

2016年(3)

2015年(11)

2014年(3)

2013年(1)

2012年(3)

2011年(17)

2010年(25)

2009年(17)

2008年(13)

2007年(14)

2006年(21)

2005年(10)

2004年(2)

分类: 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();
    }
}

参数:

ParameterDescription
usernameThe connection username to be passed to our JDBC driver to establish a connection.
passwordThe connection password to be passed to our JDBC driver to establish a connection.
urlThe connection URL to be passed to our JDBC driver to establish a connection.
driverClassNameThe fully qualified Java class name of the JDBC driver to be used.
connectionPropertiesThe 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.
<>
ParameterDefaultDescription
defaultAutoCommittrueThe default auto-commit state of connections created by this pool.
defaultReadOnlydriver defaultThe 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)
defaultTransactionIsolationdriver defaultThe default TransactionIsolation state of connections created by this pool. One of the following: (see )
  • NONE
  • READ_COMMITTED
  • READ_UNCOMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE
defaultCatalogThe default catalog of connections created by this pool.
<>
ParameterDefaultDescription
initialSize0The initial number of connections that are created when the pool is started.

Since: 1.2
maxActive8The maximum number of active connections that can be allocated from this pool at the same time, or zero for no limit.
maxIdle8The maximum number of active connections that can remain idle in the pool, without extra ones being released, or zero for no limit.
minIdle0The minimum number of active connections that can remain idle in the pool, without extra ones being created, or zero to create none.
maxWaitindefinitelyThe 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.
<>
ParameterDefaultDescription
validationQueryThe 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.
testOnBorrowtrueThe 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.
testOnReturnfalseThe indication of whether objects will be validated before being returned to the pool.
testWhileIdlefalseThe 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-1The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
numTestsPerEvictionRun3The number of objects to examine during each run of the idle object evictor thread (if any).
minEvictableIdleTimeMillis1000 * 60 * 30The 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).
<>
ParameterDefaultDescription
poolPreparedStatementsfalseEnable prepared statement pooling for this pool.
maxOpenPreparedStatementsunlimitedThe 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:

  • public PreparedStatement prepareStatement(String sql)
  • public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)

NOTE - Make sure your connection has some resources left for the other statements.

<>
ParameterDefaultDescription
accessToUnderlyingConnectionAllowedfalseControls 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.

<>
ParameterDefaultDescription
removeAbandonedfalseFlag 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.
removeAbandonedTimeout300Timeout in seconds before an abandoned connection can be removed.
logAbandonedfalseFlag 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.

阅读(2822) | 评论(1) | 转发(0) |
0

上一篇:有点难过:(

下一篇:Java 集合框架图

给主人留下些什么吧!~~

chinaunix网友2008-01-22 17:27:15

能不能翻译成中文呀