`

c3p0的使用

    博客分类:
  • c3p0
阅读更多
一、c3p0 is an easy-to-use library for making traditional JDBC drivers "enterprise-ready" by augmenting them with functionality defined by the jdbc3 spec and the optional extensions to jdbc2. In particular, c3p0 provides several useful services:
Classes which adapt traditional DriverManager-based JDBC drivers to the new javax.sql.DataSource scheme for acquiring database Connections.
Transparent pooling of Connection and PreparedStatements behind DataSources which can "wrap" around traditional drivers or arbitrary unpooled DataSources.
二、c3p0的使用
1、Instantiating and Configuring a ComboPooledDataSource
ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass("com.mysql.jdbc.Driver");
		cpds.setJdbcUrl("jdbc:mysql://localhost:3306/eims?useUnicode=true&characterEncoding =uf8");
		cpds.setUser("root");
		cpds.setPassword("root");
		Connection connection = cpds.getConnection();
		System.out.println(connection);
		System.out.println(cpds.getAcquireIncrement());
		PreparedStatement ps = connection.prepareStatement("select * from tb_product");
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
		}

2、Using the DataSources factory class
DataSource ds1 = DataSources.unpooledDataSource("jdbc:mysql://localhost:3306/eims?useUnicode=true&characterEncoding =uf8", "root", "root");
		DataSource ds2 = DataSources.pooledDataSource(ds1);
		Connection connection = ds2.getConnection();
		System.out.println(connection);
		PreparedStatement ps = connection.prepareStatement("select * from tb_product");
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
		}

三、modify c3p0 properties
1、create a file called c3p0.properties and place it at the "root" of your classpath or classloader
c3p0.properties
# turn on statement pooling
c3p0.maxStatements=150
# close pooled Connections that go unused for
# more than half an hour
c3p0.maxIdleTime=1800

2、By default, c3p0 will look for an XML configuration file in its classloader's resource path under the name "/c3p0-config.xml". That means the XML file should be placed in a directly or jar file directly named in your applications CLASSPATH, in WEB-INF/classes, or some similar location.
c3p0-config.xml
<c3p0-config>
  <default-config>
    <property name="automaticTestTable">con_test</property>
    <property name="checkoutTimeout">30000</property>
    <property name="idleConnectionTestPeriod">30</property>
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
    <property name="maxStatements">200</property>

    <user-overrides user="test-user">
      <property name="maxPoolSize">10</property>
      <property name="minPoolSize">1</property>
      <property name="maxStatements">0</property>
    </user-overrides>

  </default-config>

  <!-- This app is massive! -->
  <named-config name="intergalactoApp"> 
    <property name="acquireIncrement">50</property>
    <property name="initialPoolSize">100</property>
    <property name="minPoolSize">50</property>
    <property name="maxPoolSize">1000</property>

    <!-- intergalactoApp adopts a different approach to configuring statement caching -->
    <property name="maxStatements">0</property> 
    <property name="maxStatementsPerConnection">5</property>

    <!-- he's important, but there's only one of him -->
    <user-overrides user="master-of-the-universe"> 
      <property name="acquireIncrement">1</property>
      <property name="initialPoolSize">1</property>
      <property name="minPoolSize">1</property>
      <property name="maxPoolSize">5</property>
      <property name="maxStatementsPerConnection">50</property>
    </user-overrides>
  </named-config>
</c3p0-config>

四、各个属性所代表的意义
1、acquireIncrement
Default: 3
Determines how many connections at a time c3p0 will try to acquire when the pool is exhausted.
2、acquireRetryAttempts
Default: 30
Defines how many times c3p0 will try to acquire a new Connection from the database before giving up. If this value is less than or equal to zero, c3p0 will keep trying to fetch a Connection indefinitely.
3、acquireRetryDelay
Default: 1000
Milliseconds, time c3p0 will wait between acquire attempts.
4、autoCommitOnClose
Default: false
The JDBC spec is unforgivably silent on what should happen to unresolved, pending transactions on Connection close. C3P0's default policy is to rollback any uncommitted, pending work. (I think this is absolutely, undeniably the right policy, but there is no consensus among JDBC driver vendors.) Setting autoCommitOnClose to true causes uncommitted pending work to be committed, rather than rolled back on Connection close. [Note: Since the spec is absurdly unclear on this question, application authors who wish to avoid bugs and inconsistent behavior should ensure that all transactions are explicitly either committed or rolled-back before close is called.]
5、automaticTestTable
Default: null
If provided, c3p0 will create an empty table of the specified name, and use queries against that table to test the Connection. If automaticTestTable is provided, c3p0 will generate its own test query, therefore any preferredTestQuery set will be ignored. You should not work with the named table after c3p0 creates it; it should be strictly for c3p0's use in testing your Connection. (If you define your own ConnectionTester, it must implement the QueryConnectionTester interface for this parameter to be useful.)
6、breakAfterAcquireFailure
Default: false
If true, a pooled DataSource will declare itself broken and be permanently closed if a Connection cannot be obtained from the database after making acquireRetryAttempts to acquire one. If false, failure to obtain a Connection will cause all Threads waiting for the pool to acquire a Connection to throw an Exception, but the DataSource will remain valid, and will attempt to acquire again following a call to getConnection().
7、checkoutTimeout
Default: 0
The number of milliseconds a client calling getConnection() will wait for a Connection to be checked-in or acquired when the pool is exhausted. Zero means wait indefinitely. Setting any positive value will cause the getConnection() call to time-out and break with an SQLException after the specified number of milliseconds.
8、connectionCustomizerClassName
Default: null
The fully qualified class-name of an implememtation of the ConnectionCustomizer interface, which users can implement to set up Connections when they are acquired from the database, or on check-out, and potentially to clean things up on check-in and Connection destruction. If standard Connection properties (holdability, readOnly, or transactionIsolation) are set in the ConnectionCustomizer's onAcquire() method, these will override the Connection default values.
9、connectionTesterClassName
Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester
The fully qualified class-name of an implememtation of the ConnectionTester interface, or QueryConnectionTester if you would like instances to have access to a user-configured preferredTestQuery. This can be used to customize how c3p0 DataSources test Connections, but with the introduction of automaticTestTable and preferredTestQuery configuration parameters, "rolling your own" should be overkill for most users.
10、debugUnreturnedConnectionStackTraces
Default: false
If true, and if unreturnedConnectionTimeout is set to a positive value, then the pool will capture the stack trace (via an Exception) of all Connection checkouts, and the stack traces will be printed when unreturned checked-out Connections timeout. This is intended to debug applications with Connection leaks, that is applications that occasionally fail to return Connections, leading to pool growth, and eventually exhaustion (when the pool hits maxPoolSize with all Connections checked-out and lost). This parameter should only be set while debugging, as capturing the stack trace will slow down every Connection check-out.
Does Not Support Per-User Overrides.
11、factoryClassLocation
Default: null
DataSources that will be bound by JNDI and use that API's Referenceable interface to store themselves may specify a URL from which the class capable of dereferencing a them may be loaded. If (as is usually the case) the c3p0 libraries will be locally available to the JNDI service, leave this set as null.
Does Not Support Per-User Overrides.
12、forceIgnoreUnresolvedTransactions
Default: false
Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs. This is a terrible setting, leave it alone unless absolutely necessary. It is here to workaround broken databases / JDBC drivers that do not properly support transactions, but that allow Connections' autoCommit flags to go to false regardless. If you are using a database that supports transactions "partially" (this is oxymoronic, as the whole point of transactions is to perform operations reliably and completely, but nonetheless such databases are out there), if you feel comfortable ignoring the fact that Connections with autoCommit == false may be in the middle of transactions and may hold locks and other resources, you may turn off c3p0's wise default behavior, which is to protect itself, as well as the usability and consistency of the database, by either rolling back (default) or committing (see c3p0.autoCommitOnClose above) unresolved transactions. This should only be set to true when you are sure you are using a database that allows Connections' autoCommit flag to go to false, but offers no other meaningful support of transactions. Otherwise setting this to true is just a bad idea.
13、idleConnectionTestPeriod
Default: 0
If this is a number greater than 0, c3p0 will test all idle, pooled but unchecked-out connections, every this number of seconds.
14、initialPoolSize
Default: 3
Number of Connections a pool will try to acquire upon startup. Should be between minPoolSize and maxPoolSize.
15、maxAdministrativeTaskTime
Default: 0
Seconds before c3p0's thread pool will try to interrupt an apparently hung task. Rarely useful. Many of c3p0's functions are not performed by client threads, but asynchronously by an internal thread pool. c3p0's asynchrony enhances client performance directly, and minimizes the length of time that critical locks are held by ensuring that slow jdbc operations are performed in non-lock-holding threads. If, however, some of these tasks "hang", that is they neither succeed nor fail with an Exception for a prolonged period of time, c3p0's thread pool can become exhausted and administrative tasks backed up. If the tasks are simply slow, the best way to resolve the problem is to increase the number of threads, via numHelperThreads. But if tasks sometimes hang indefinitely, you can use this parameter to force a call to the task thread's interrupt() method if a task exceeds a set time limit. [c3p0 will eventually recover from hung tasks anyway by signalling an "APPARENT DEADLOCK" (you'll see it as a warning in the logs), replacing the thread pool task threads, and interrupt()ing the original threads. But letting the pool go into APPARENT DEADLOCK and then recover means that for some periods, c3p0's performance will be impaired. So if you're seeing these messages, increasing numHelperThreads and setting maxAdministrativeTaskTime might help. maxAdministrativeTaskTime should be large enough that any resonable attempt to acquire a Connection from the database, to test a Connection, or two destroy a Connection, would be expected to succeed or fail within the time set. Zero (the default) means tasks are never interrupted, which is the best and safest policy under most circumstances. If tasks are just slow, allocate more threads. If tasks are hanging forever, try to figure out why, and maybe setting maxAdministrativeTaskTime can help in the meantime.
Does Not Support Per-User Overrides.
16、maxConnectionAge
Default: 0
Seconds, effectively a time to live. A Connection older than maxConnectionAge will be destroyed and purged from the pool. This differs from maxIdleTime in that it refers to absolute age. Even a Connection which has not been much idle will be purged from the pool if it exceeds maxConnectionAge. Zero means no maximum absolute age is enforced.
17、maxIdleTime
Default: 0
Seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire.
18、maxIdleTimeExcessConnections
Default: 0
Number of seconds that Connections in excess of minPoolSize should be permitted to remain idle in the pool before being culled. Intended for applications that wish to aggressively minimize the number of open Connections, shrinking the pool back towards minPoolSize if, following a spike, the load level diminishes and Connections acquired are no longer needed. If maxIdleTime is set, maxIdleTimeExcessConnections should be smaller if the parameter is to have any effect. Zero means no enforcement, excess Connections are not idled out.
19、maxPoolSize
Default: 15
Maximum number of Connections a pool will maintain at any given time.
20、maxStatements
Default: 0
The size of c3p0's global PreparedStatement cache. If both maxStatements and maxStatementsPerConnection are zero, statement caching will not be enabled. If maxStatements is zero but maxStatementsPerConnection is a non-zero value, statement caching will be enabled, but no global limit will be enforced, only the per-connection maximum. maxStatements controls the total number of Statements cached, for all Connections. If set, it should be a fairly large number, as each pooled Connection requires its own, distinct flock of cached statements. As a guide, consider how many distinct PreparedStatements are used frequently in your application, and multiply that number by maxPoolSize to arrive at an appropriate value. Though maxStatements is the JDBC standard parameter for controlling statement caching, users may find c3p0's alternative maxStatementsPerConnection more intuitive to use.
21、maxStatementsPerConnection
Default: 0
The number of PreparedStatements c3p0 will cache for a single pooled Connection. If both maxStatements and maxStatementsPerConnection are zero, statement caching will not be enabled. If maxStatementsPerConnection is zero but maxStatements is a non-zero value, statement caching will be enabled, and a global limit enforced, but otherwise no limit will be set on the number of cached statements for a single Connection. If set, maxStatementsPerConnection should be set to about the number distinct PreparedStatements that are used frequently in your application, plus two or three extra so infrequently statements don't force the more common cached statements to be culled. Though maxStatements is the JDBC standard parameter for controlling statement caching, users may find maxStatementsPerConnection more intuitive to use.
22、minPoolSize
Default: 3
Minimum number of Connections a pool will maintain at any given time.
23、numHelperThreads
Default: 3
c3p0 is very asynchronous. Slow JDBC operations are generally performed by helper threads that don't hold contended locks. Spreading these operations over multiple threads can significantly improve performance by allowing multiple operations to be performed simultaneously.
Does Not Support Per-User Overrides.
24、overrideDefaultUser
Default: null
Forces the username that should by PooledDataSources when a user calls the default getConnection() method. This is primarily useful when applications are pooling Connections from a non-c3p0 unpooled DataSource. Applications that use ComboPooledDataSource, or that wrap any c3p0-implemented unpooled DataSource can use the simple user property.
Does Not Support Per-User Overrides.
25、overrideDefaultPassword
Default: null
Forces the password that should by PooledDataSources when a user calls the default getConnection() method. This is primarily useful when applications are pooling Connections from a non-c3p0 unpooled DataSource. Applications that use ComboPooledDataSource, or that wrap any c3p0-implemented unpooled DataSource can use the simple password property.
Does Not Support Per-User Overrides.
26、password
Default: null
For applications using ComboPooledDataSource or any c3p0-implemented unpooled DataSources — DriverManagerDataSource or the DataSource returned by DataSources.unpooledDataSource( ... ) — defines the password that will be used for the DataSource's default getConnection() method. (See also user.)
Does Not Support Per-User Overrides.
27、preferredTestQuery
Default: null
Defines the query that will be executed for all connection tests, if the default ConnectionTester (or some other implementation of QueryConnectionTester, or better yet FullQueryConnectionTester) is being used. Defining a preferredTestQuery that will execute quickly in your database may dramatically speed up Connection tests. (If no preferredTestQuery is set, the default ConnectionTester executes a getTables() call on the Connection's DatabaseMetaData. Depending on your database, this may execute more slowly than a "normal" database query.) NOTE: The table against which your preferredTestQuery will be run must exist in the database schema prior to your initialization of your DataSource. If your application defines its own schema, try automaticTestTable instead.
28、propertyCycle
Default: 0
Maximum time in seconds before user configuration constraints are enforced. Determines how frequently maxConnectionAge, maxIdleTime, maxIdleTimeExcessConnections, unreturnedConnectionTimeout are enforced. c3p0 periodically checks the age of Connections to see whether they've timed out. This parameter determines the period. Zero means automatic: A suitable period will be determined by c3p0. [You can call getEffectivePropertyCycle...() methods on a c3p0 PooledDataSource to find the period automatically chosen.]
29、testConnectionOnCheckin
Default: false
If true, an operation will be performed asynchronously at every connection checkin to verify that the connection is valid. Use in combination with idleConnectionTestPeriod for quite reliable, always asynchronous Connection testing. Also, setting an automaticTestTable or preferredTestQuery will usually speed up all connection tests.
30、testConnectionOnCheckout
Default: false
Use only if necessary. Expensive. If true, an operation will be performed at every connection checkout to verify that the connection is valid. Better choice: verify connections periodically using idleConnectionTestPeriod. Also, setting an automaticTestTable or preferredTestQuery will usually speed up all connection tests.
31、unreturnedConnectionTimeout
Default: 0
Seconds. If set, if an application checks out but then fails to check-in [i.e. close()] a Connection within the specified period of time, the pool will unceremoniously destroy() the Connection. This permits applications with occasional Connection leaks to survive, rather than eventually exhausting the Connection pool. And that's a shame. Zero means no timeout, applications are expected to close() their own Connections. Obviously, if a non-zero value is set, it should be to a value longer than any Connection should reasonably be checked-out. Otherwise, the pool will occasionally kill Connections in active use, which is bad. This is basically a bad idea, but it's a commonly requested feature. Fix your $%!@% applications so they don't leak Connections! Use this temporarily in combination with debugUnreturnedConnectionStackTraces to figure out where Connections are being checked-out that don't make it back into the pool!
32、user
Default: null
For applications using ComboPooledDataSource or any c3p0-implemented unpooled DataSources — DriverManagerDataSource or the DataSource returned by DataSources.unpooledDataSource() — defines the username that will be used for the DataSource's default getConnection() method. (See also password.)
Does Not Support Per-User Overrides.
33、usesTraditionalReflectiveProxies
Default: false
c3p0 originally used reflective dynamic proxies for implementations of Connections and other JDBC interfaces. As of c3p0-0.8.5, non-reflective, code-generated implementations are used instead. As this was a major change, and the old codebase had been extensively used and tested, this parameter was added to allow users to revert of they had problems. The new, non-reflexive implementation is faster, and has now been widely deployed and tested, so it is unlikely that this parameter will be useful. Both the old reflective and newer non-reflective codebases are being maintained, but support for the older codebase may (or may not) be dropped in the future.
分享到:
评论

相关推荐

    C3P0 使用详细说明

    对于初学者来说,理解并掌握C3P0的使用是数据库操作中非常重要的一步。下面将详细介绍C3P0连接池的基本概念、配置、使用方法以及常见问题。 一、C3P0简介 C3P0是由M EHood开发的一款优秀的数据库连接池,其主要功能...

    c3p0使用简介

    ### c3p0 使用简介 #### 一、概述 c3p0 是一款开源的 JDBC 连接池组件,常用于 Java 应用程序中管理数据库连接资源。它随 Hibernate 发布,在 lib 目录下提供了针对 JDBC 3 和 JDBC 2 扩展规范的数据源对象,这些...

    C3P0使用,C3P0源码及实例

    在实际应用中,我们可以使用Spring框架来集成C3P0,以下是一个简单的Spring配置示例: ```xml &lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt; &lt;!-- ...

    C3P0使用所需要的jar包

    在Java应用程序中,C3P0可以帮助我们更有效地管理和使用数据库连接,避免频繁创建和关闭连接导致的性能损失。下面将详细介绍C3P0的核心功能、配置以及与MySQL数据库的结合使用。 C3P0的主要功能包括: 1. **连接池...

    C3P0连接池配置需要的jar包

    C3P0库依赖于其他几个JAR包来实现其功能,包括`c3p0-0.9.2.1.jar`、`hibernate-c3p0-4.0.0.Final[1].jar`以及`mchange-commons-java-0.2.3.4.jar`。 1. **c3p0-0.9.2.1.jar**: 这是C3P0的主要库文件,包含了C3P0的...

    c3p0连接池jar包

    4. **C3P0使用**: - 添加依赖:在项目中引入C3P0的JAR包,如`lib/c3p0-*.jar`,同时可能需要包含其他的依赖,如`lib/mchange-commons-java-*.jar`。 - 创建数据源:通过`...

    DB2驱动和c3p0使用方法

    要使用C3P0,你需要引入c3p0的JAR包,如`c3p0-0.9.5.x.jar`。 配置C3P0连接池的基本步骤如下: 1. 添加C3P0库到项目类路径。 2. 创建数据源配置,定义连接池参数,如初始化大小、最大大小、超时时间等。以下是一个...

    c3p0工具包.rar

    3. **c3p0使用步骤** - **添加依赖**:将c3p0及相关依赖库(如本例中的三个JAR文件)引入项目类路径。 - **配置属性**:在配置文件中设置c3p0的相关参数,如数据库URL、用户名、密码以及连接池的大小等。 - **...

    c3p0连接池

    **三、c3p0使用步骤** 1. 添加依赖:在项目中引入c3p0的jar包或通过Maven、Gradle等构建工具添加依赖。 2. 配置c3p0:在配置文件中设定数据库连接信息和池化参数,例如: ``` ...

    c3p0-c3p0-0.9.5.2.zip

    四、c3p0使用示例 以下是一个基本的c3p0配置和使用示例: ```java import com.mchange.v2.c3p0.ComboPooledDataSource; Properties props = new Properties(); props.setProperty("driverClass", ...

    c3p0需要的三个包

    David Stone维护的通用工具库,C3P0使用了其中的一些组件来实现其功能,如异常处理和配置解析等。这个库是C3P0依赖的一部分,确保C3P0能够正常工作。 3. **c3p0-oracle-thin-extras-0.9.2.1.jar**:这个包是专门为...

    c3p0-1 lib.rar

    三、c3p0使用步骤 1. 引入依赖:在项目中引入c3p0的jar包,例如,如果你使用的是Maven,可以在pom.xml文件中添加如下依赖: ```xml &lt;groupId&gt;com.mchange&lt;/groupId&gt; &lt;artifactId&gt;c3p0 &lt;version&gt;0.9.5.5 ``` 2....

    c3p0数据库连接池所需jar包

    四、C3P0使用示例 以下是一个简单的C3P0配置和使用的Java代码示例: ```java import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0DataSource { public static ComboPooledDataSource ...

    c3p0 jar包及xml文件

    2. **commons-pool-1.5.6.jar**:Apache Commons Pool 是一个通用的对象池服务,c3p0使用它来实现数据库连接的池化。对象池技术允许重复使用已经创建的对象,避免了频繁创建和销毁对象带来的性能损失。 **c3p0配置...

    配置Hibernate使用C3P0连接池

    **配置Hibernate使用C3P0连接池** 在Java Web开发中,数据库连接管理是一个至关重要的环节,有效地管理和控制数据库连接可以提高应用的性能和稳定性。Hibernate作为一款强大的ORM(对象关系映射)框架,提供了与...

    使用c3p0简化链接数据库链接

    **使用C3P0简化数据库连接** C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。C3P0的主要优点在于它的易用性和灵活性,使得开发者无需在XML配置文件中设置大量复杂的参数...

    c3p0-0.9.5.2

    **四、c3p0使用步骤** 1. 添加依赖:将c3p0-0.9.5.2的jar包引入项目。 2. 初始化数据源:通过`ComboPooledDataSource`创建数据源实例,设置必要的配置属性。 3. 获取数据库连接:使用`getConnection()`方法从数据...

    c3p0连接池示例

    ### 三、c3p0使用步骤 1. 添加依赖:在项目中引入c3p0的JAR包或对应的Maven/Gradle依赖。 2. 配置属性:通过 ComboPooledDataSource 类的setter方法设置数据库连接的URL、用户名、密码以及c3p0的配置参数。 3. 创建...

    c3p0连接池相关jar包

    **三、c3p0使用步骤** 1. **引入依赖**: 在项目中引入c3p0的jar包,如`c3p0-0.9.5.2.bin`。 2. **配置数据源**: 创建`ComboPooledDataSource`实例,并设置相关配置参数。 3. **获取与释放连接**: 使用数据源的`...

Global site tag (gtag.js) - Google Analytics