### c3p0 Properties File Example Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Create a c3p0.properties file in your classpath to override default settings. This example enables statement pooling and sets a maximum idle time for connections. ```properties # turn on statement pooling c3p0.maxStatements=150 # close pooled Connections that go unused for # more than half an hour c3p0.maxIdleTime=1800 ``` -------------------------------- ### Add Parameter to example/c3p0-service.xml Source: https://github.com/swaldman/c3p0/blob/0.13.x/adding-properties.md Optionally, add the new parameter to the example c3p0-service.xml configuration file. ```xml ``` -------------------------------- ### ConnectionCustomizer using initSql Extension Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Example implementation of a ConnectionCustomizer that executes SQL defined in the 'initSql' extension upon connection checkout. ```java package mypkg; import java.sql.*; import com.mchange.v2.c3p0.AbstractConnectionCustomizer; public class InitSqlConnectionCustomizer extends AbstractConnectionCustomizer { private String getInitSql( String parentDataSourceIdentityToken ) { return (String) extensionsForToken( parentDataSourceIdentityToken ).get ( "initSql" ); } public void onCheckOut( Connection c, String parentDataSourceIdentityToken ) throws Exception { String initSql = getInitSql( parentDataSourceIdentityToken ); if ( initSql != null ) { Statement stmt = null; try { stmt = c.createStatement(); stmt.executeUpdate( initSql ); } finally { if ( stmt != null ) stmt.close(); } } } } ``` -------------------------------- ### DataSources Factory Example: Unpooled and Pooled DataSources Source: https://context7.com/swaldman/c3p0/llms.txt Demonstrates building an unpooled DataSource from a JDBC URL and credentials, then wrapping it with a c3p0 pool using a map of override properties. Includes usage and cleanup. ```java import com.mchange.v2.c3p0.*; import javax.sql.DataSource; import java.sql.*; import java.util.HashMap; import java.util.Map; public class FactoryExample { public static void main(String[] args) throws Exception { // 1. Build an unpooled DataSource from URL + credentials DataSource unpooled = DataSources.unpooledDataSource( "jdbc:postgresql://localhost:5432/mydb", "appuser", "s3cr3t" ); // 2. Wrap it with a pool, overriding selected properties Map overrides = new HashMap<>(); overrides.put("maxPoolSize", 25); overrides.put("maxStatements", 200); // enable statement cache overrides.put("testConnectionOnCheckout", true); overrides.put("maxIdleTime", 1800); DataSource pooled = DataSources.pooledDataSource(unpooled, overrides); // 3. Use it try (Connection con = pooled.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT count(*) FROM orders")) { if (rs.next()) System.out.println("Order count: " + rs.getLong(1)); // Output: Order count: 4271 } // 4. Clean up when the application shuts down DataSources.destroy(pooled); } } ``` -------------------------------- ### HOCON Logging Configuration Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Example of configuring c3p0 logging using HOCON, demonstrating both properties-file-ish and scoped syntax for setting the MLog implementation. ```hocon # properties-file-ish specification com.mchange.v2.log.MLog=com.mchange.v2.log.log4j.Log4jMLog # scoped specification of the same com { mchange { v2 { log { MLog="com.mchange.v2.log.log4j.Log4jMLog" } } } } ``` -------------------------------- ### Build c3p0 JAR Source: https://github.com/swaldman/c3p0/blob/0.13.x/README.md Use this command to build the c3p0 library into a JAR file. Ensure you have mill installed and are in the repository directory. ```plaintext $ mill jar ``` -------------------------------- ### Implement ConnectionCustomizer for Connection Lifecycle Hooks Source: https://context7.com/swaldman/c3p0/llms.txt Extend AbstractConnectionCustomizer to define custom logic for connection events. This example sets the time zone on acquire and manages the search_path and role on checkout and checkin. ```java import com.mchange.v2.c3p0.AbstractConnectionCustomizer; import java.sql.Connection; import java.sql.Statement; /** * Sets a session-level role and search_path on every checked-out connection. * Register via: cpds.setConnectionCustomizerClassName(TenantConnectionCustomizer.class.getName()) */ public class TenantConnectionCustomizer extends AbstractConnectionCustomizer { @Override public void onAcquire(Connection c, String parentDataSourceIdentityToken) throws Exception { // Called once when a physical connection is created try (Statement s = c.createStatement()) { s.execute("SET TIME ZONE 'UTC'"); } System.out.println("Connection acquired and initialized: " + c); } @Override public void onCheckOut(Connection c, String parentDataSourceIdentityToken) throws Exception { // Called on every checkout; use extensions map for per-DS config String schema = (String) extensionsForToken(parentDataSourceIdentityToken) .getOrDefault("schema", "public"); try (Statement s = c.createStatement()) { s.execute("SET search_path TO " + schema); } } @Override public void onCheckIn(Connection c, String parentDataSourceIdentityToken) throws Exception { // Called after client returns the connection; reset session state try (Statement s = c.createStatement()) { s.execute("SET search_path TO public"); s.execute("RESET ROLE"); } } @Override public void onDestroy(Connection c, String parentDataSourceIdentityToken) throws Exception { System.out.println("Connection destroyed: " + c); } } ``` -------------------------------- ### Configuring c3p0 with a Custom Connection Tester Source: https://context7.com/swaldman/c3p0/llms.txt Configure a ComboPooledDataSource to use the custom PingConnectionTester and set a preferred test query. This example also enables connection testing on checkout and sets an idle connection test period. ```java ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setJdbcUrl("jdbc:postgresql://localhost/mydb"); cpds.setUser("appuser"); cpds.setPassword("s3cr3t"); cpds.setConnectionTesterClassName(PingConnectionTester.class.getName()); cpds.setPreferredTestQuery("SELECT 1"); // passed to activeCheckConnection cpds.setTestConnectionOnCheckout(true); cpds.setIdleConnectionTestPeriod(60); // test idle connections every 60 s ``` -------------------------------- ### HOCON Dot Notation for c3p0 Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html An alternative HOCON syntax using dot notation to configure c3p0 properties. This is equivalent to the scoped HOCON example and the properties file format. ```hocon # equivalent to the example above, and # identical to the properties file format. c3p0.maxStatements=150 c3p0.maxIdleTime=1800 ``` -------------------------------- ### HOCON Configuration for c3p0 Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Configure c3p0 using HOCON format, typically in application.conf or c3p0.conf. This requires bundling the Typesafe config library. This example enables statement pooling and sets a maximum idle time. ```hocon c3p0 { # turn on statement pooling maxStatements=150 # close pooled Connections that go unused for # more than half an hour maxIdleTime=1800 } ``` -------------------------------- ### Build c3p0 Documentation Source: https://github.com/swaldman/c3p0/blob/0.13.x/README.md Generate the project documentation, which can then be opened in your browser at 'out/doc/docroot.dest/index.html'. ```plaintext $ mill doc.docroot ``` -------------------------------- ### Mixing c3p0 Configuration in Properties File Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Demonstrates how to mix named configurations, per-user overrides, and user-defined extensions within a properties-style configuration file. ```properties c3p0.maxPoolSize=30 c3p0.extensions.initSql=SET SCHEMA 'default' c3p0.named-configs.intergalactoApp.maxPoolSize=1000 c3p0.named-configs.intergalactoApp.extensions.initSql=SET SCHEMA 'intergalacto' c3p0.named-configs.user-overrides.steve.maxPoolSize=20 ``` -------------------------------- ### Get All PooledDataSources using C3P0Registry Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Use getPooledDataSources to retrieve a Set of all active c3p0 DataSources. This is useful if you have only one DataSource or can distinguish them by configuration. ```java Set allPooledDataSources = C3P0Registry.getPooledDataSources(); ``` -------------------------------- ### Mixing c3p0 Configuration in XML File Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Shows how to integrate named configurations, per-user overrides, and user-defined extensions within an XML configuration. ```xml 30 SET SCHEMA 'default' 1000 20 SET SCHEMA 'intergalacto' ``` -------------------------------- ### Get PooledDataSource by Name using C3P0Registry Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Use pooledDataSourceByName to retrieve a specific c3p0 DataSource by its name. Ensure the dataSourceName is unique if you expect a single result. ```java PooledDataSource pds = C3P0Registry.pooledDataSourceByName( "myDataSourceName" ); ``` -------------------------------- ### Sample ConnectionCustomizer Implementation Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Implement this interface to modify or track Connections just after they are checked out from the database, just prior to being handed to clients on checkout, just prior to being returned to the pool on check-in, and just prior to final destruction by the pool. Implementations should be immutable and have public no-argument constructors. ```java import com.mchange.v2.c3p0.*; import java.sql.Connection; public class VerboseConnectionCustomizer { public void onAcquire( Connection c, String pdsIdt ) { System.err.println("Acquired " + c + " \[" + pdsIdt + "\]"); // override the default transaction isolation of // newly acquired Connections c.setTransactionIsolation( Connection.REPEATABLE_READ ); } public void onDestroy( Connection c, String pdsIdt ) { System.err.println("Destroying " + c + " \[" + pdsIdt + "\]"); } public void onCheckOut( Connection c, String pdsIdt ) { System.err.println("Checked out " + c + " \[" + pdsIdt + "\]"); } public void onCheckIn( Connection c, String pdsIdt ) { System.err.println("Checking in " + c + " \[" + pdsIdt + "\]"); } } ``` -------------------------------- ### System Properties for c3p0 Configuration Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Override c3p0 settings by defining system properties when launching your Java application. This example sets statement pooling and idle time properties. ```java swaldman% java -Dc3p0.maxStatements=150 -Dc3p0.maxIdleTime=1800 example.MyC3P0App ``` -------------------------------- ### Mixing c3p0 Configuration in HOCON File Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Illustrates combining named configurations, per-user overrides, and user-defined extensions using HOCON syntax. ```hocon c3p0 { maxPoolSize=30 extensions { initSql=SET SCHEMA 'default' } named-configs { intergalactoApp { maxPoolSize=1000 user-overrides { steve { maxPoolSize=20 } } extensions { initSql=SET SCHEMA 'intergalacto' } } } } ``` -------------------------------- ### Custom Connection Validation with PingConnectionTester Source: https://context7.com/swaldman/c3p0/llms.txt Extend AbstractConnectionTester to provide a custom connection validation query. This example uses a simple 'SELECT 1' query and distinguishes between connection errors and database outages. ```java import com.mchange.v2.c3p0.AbstractConnectionTester; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /** * Validates connections by running a lightweight vendor-specific ping query. * Register via: cpds.setConnectionTesterClassName(PingConnectionTester.class.getName()) */ public class PingConnectionTester extends AbstractConnectionTester { @Override public int activeCheckConnection(Connection c, String preferredTestQuery, Throwable[] rootCauseOutParamHolder) { String query = (preferredTestQuery != null) ? preferredTestQuery : "SELECT 1"; try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery(query)) { return CONNECTION_IS_OKAY; } catch (Exception e) { if (rootCauseOutParamHolder != null) rootCauseOutParamHolder[0] = e; // Distinguish transient connection error from complete database outage String msg = e.getMessage(); if (msg != null && msg.contains("FATAL")) return DATABASE_IS_INVALID; return CONNECTION_IS_INVALID; } } @Override public int statusOnException(Connection c, Throwable t, String preferredTestQuery, Throwable[] rootCauseOutParamHolder) { if (t instanceof java.sql.SQLTransientConnectionException) return CONNECTION_IS_INVALID; if (t instanceof java.sql.SQLException) { String state = ((java.sql.SQLException) t).getSQLState(); if (state != null && state.startsWith("08")) // connection exception class return CONNECTION_IS_INVALID; } return CONNECTION_IS_OKAY; } } ``` -------------------------------- ### Using c3p0 with Per-User Pools and Querying Pool Status Source: https://context7.com/swaldman/c3p0/llms.txt Demonstrates creating a `ComboPooledDataSource`, obtaining connections for default and specific users, and querying the status of individual pools. Ensure to close the `ComboPooledDataSource` when done. ```java import com.mchange.v2.c3p0.*; import java.sql.*; ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setJdbcUrl("jdbc:postgresql://localhost/mydb"); cpds.setUser("defaultuser"); cpds.setPassword("default_pass"); cpds.setMaxPoolSize(20); // Default-user pool try (Connection c = cpds.getConnection()) { /* ... */ } // Separate pool for "batchjob" (governed by user-overrides in config) try (Connection c = cpds.getConnection("batchjob", "batch_pass")) { /* ... */ } // Query individual pools System.out.println("Default-user busy : " + cpds.getNumBusyConnectionsDefaultUser()); System.out.println("batchjob busy : " + cpds.getNumBusyConnections("batchjob", "batch_pass")); System.out.println("All-users total : " + cpds.getNumConnectionsAllUsers()); cpds.close(); ``` -------------------------------- ### ComboPooledDataSource Basic Pool Setup Source: https://context7.com/swaldman/c3p0/llms.txt Configure and use ComboPooledDataSource for basic connection pooling. This JavaBean can be configured programmatically via setters before obtaining connections. It implements PooledDataSource and AutoCloseable for use in try-with-resources. ```java import com.mchange.v2.c3p0.*; import java.sql.*; public class AppDataSource { public static ComboPooledDataSource buildDataSource() throws Exception { ComboPooledDataSource cpds = new ComboPooledDataSource(); // Required connection settings cpds.setDriverClass("org.postgresql.Driver"); // loads the JDBC driver cpds.setJdbcUrl("jdbc:postgresql://localhost:5432/mydb"); cpds.setUser("appuser"); cpds.setPassword("s3cr3t"); // Pool sizing cpds.setInitialPoolSize(5); cpds.setMinPoolSize(5); cpds.setMaxPoolSize(30); cpds.setAcquireIncrement(5); // grow by 5 when exhausted // Connection age management cpds.setMaxIdleTime(1800); // expire after 30 min idle cpds.setMaxConnectionAge(3600); // hard cap: 1 hour lifetime cpds.setMaxIdleTimeExcessConnections(300); // trim extras after 5 min // Connection testing (recommended) cpds.setTestConnectionOnCheckout(true); cpds.setConnectionIsValidTimeout(5); // seconds for isValid() // PreparedStatement caching cpds.setMaxStatements(200); // global statement cache cpds.setMaxStatementsPerConnection(20); // per-connection limit // Reliability tuning cpds.setAcquireRetryAttempts(10); cpds.setAcquireRetryDelay(500); // ms between retries cpds.setCheckoutTimeout(5000); // ms; 0 = block forever cpds.setNumHelperThreads(5); // background thread pool return cpds; } public static void main(String[] args) throws Exception { try (ComboPooledDataSource cpds = buildDataSource()) { // Use just like any javax.sql.DataSource try (Connection con = cpds.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id, name FROM users WHERE active = ?")) { ps.setBoolean(1, true); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { System.out.printf("id=%d name=%s%n", rs.getInt(1), rs.getString(2)); } } } // Output: id=1 name=Alice // id=2 name=Bob } // cpds.close() called automatically } } ``` -------------------------------- ### Invoke Oracle-specific API on Raw Connection Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html This example demonstrates how to use rawConnectionOperation to invoke a static method on an Oracle CLOB object. Ensure proper cleanup of any non-standard resources returned by vendor-specific methods. ```java C3P0ProxyConnection castCon = (C3P0ProxyConnection) c3p0DataSource.getConnection(); Method m = CLOB.class.getMethod("createTemporary", new Class[]{Connection.class, boolean.class, int.class}); Object[] args = new Object[]{C3P0ProxyConnection.RAW_CONNECTION, Boolean.valueOf( true ), new Integer( 10 )}; CLOB oracleCLOB = (CLOB) castCon.rawConnectionOperation(m, null, args); ``` -------------------------------- ### Define Named Configurations (Properties) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define default and named configurations using properties-style files. This method is straightforward for simple configurations. ```properties # define default-config param values c3p0.maxPoolSize=30 c3p0.minPoolSize=10 # define params for a named config called intergalactoApp c3p0.named-configs.intergalactoApp.maxPoolSize=1000 c3p0.named-configs.intergalactoApp.minPoolSize=100 c3p0.named-configs.intergalactoApp.numHelperThreads=50 # define params for a named config called littleTeenyApp c3p0.named-configs.littleTeenyApp.maxPoolSize=5 c3p0.named-configs.littleTeenyApp.minPoolSize=2 ``` -------------------------------- ### Instantiate PooledDataSource with Named Configuration (Java) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Instantiate a c3p0 PooledDataSource using a specific named configuration. This allows for distinct connection pool settings for different parts of an application. ```java ComboPooledDataSource cpds = new ComboPooledDataSource("intergalactoApp"); ``` ```java DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoApp" ); ``` -------------------------------- ### Run c3p0 Basic Benchmark Source: https://github.com/swaldman/c3p0/blob/0.13.x/README.md This command runs c3p0's most basic and common test, exercising various operations and timing them. ```plaintext $ mill test.c3p0Benchmark ``` -------------------------------- ### Instantiate ComboPooledDataSource Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Create a c3p0 pooled DataSource by instantiating ComboPooledDataSource and setting essential properties like jdbcUrl, user, and password. The driverClass should be set if using an old-style JDBC driver that is not preloaded. ```java ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" ); cpds.setUser("swaldman"); cpds.setPassword("test-password"); // the settings below are optional -- c3p0 can work with defaults cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(20); ``` -------------------------------- ### Define Per-User Configurations (Properties) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define user-specific overrides for default configurations using properties-style files. This allows for granular control over connection pools based on authenticated users. ```properties # define default-config param values c3p0.maxPoolSize=30 c3p0.minPoolSize=10 # define params for a user called 'steve' c3p0.user-overrides.steve.maxPoolSize=15 c3p0.user-overrides.steve.minPoolSize=5 # define params for a user called 'ramona' c3p0.user-overrides.ramona.maxPoolSize=50 c3p0.user-overrides.ramona.minPoolSize=20 ``` -------------------------------- ### Properties-style Configuration for Extensions Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define user extensions in a properties-style configuration file. Keys and values are directly specified. ```properties c3p0.extensions.initSql=SET SCHEMA 'foo' c3p0.extensions.timezone=PDT ``` -------------------------------- ### Define Per-User Configurations (XML) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define user-specific overrides for default configurations using XML files. This is suitable for applications that manage user-specific connection pool behavior via XML. ```xml 30 10 15 5 50 20 ``` -------------------------------- ### Basic c3p0 DataSource Configuration Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Configure a ComboPooledDataSource with essential JDBC connection details. Ensure the correct driver class and connection URL are set. ```java import com.mchange.v2.c3p0.*; ... ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:postgresql://localhost:5432/testdb" ); cpds.setUser("dbuser"); cpds.setPassword("dbpassword"); ``` -------------------------------- ### XML Configuration for Extensions Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define user extensions in an XML configuration file using nested property tags. ```xml SET SCHEMA 'foo' PDT ``` -------------------------------- ### c3p0 Configuration with XML Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html This XML file defines c3p0 connection pool configurations, including default settings and named configurations for specific applications. It demonstrates how to set properties like connection testing, timeouts, pool sizes, and statement caching. ```xml con_test 30000 30 10 30 100 10 200 10 1 0 50 100 50 1000 0 5 1 1 1 5 50 ``` -------------------------------- ### Define Named Configurations (XML) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define default and named configurations using XML files. This is a common approach for enterprise applications requiring structured configuration. ```xml 30 10 1000 100 50 5 2 ``` -------------------------------- ### c3p0 Global Defaults Configuration Source: https://context7.com/swaldman/c3p0/llms.txt Configure global default properties for all c3p0 DataSources by placing a `c3p0.properties` file at the root of the classpath. Properties prefixed with `c3p0.` set these defaults. ```properties # c3p0.properties (classpath root) # Global defaults applied to all DataSources c3p0.initialPoolSize=5 c3p0.minPoolSize=5 c3p0.maxPoolSize=20 c3p0.acquireIncrement=5 # Connection lifetime management c3p0.maxIdleTime=1800 c3p0.maxConnectionAge=3600 # Connection testing c3p0.testConnectionOnCheckout=true c3p0.connectionIsValidTimeout=5 c3p0.idleConnectionTestPeriod=60 # Statement caching c3p0.maxStatements=200 c3p0.maxStatementsPerConnection=20 # Recovery c3p0.acquireRetryAttempts=10 c3p0.acquireRetryDelay=500 c3p0.breakAfterAcquireFailure=false # Leaked connection debugging c3p0.unreturnedConnectionTimeout=30 c3p0.debugUnreturnedConnectionStackTraces=true ``` -------------------------------- ### Create Pooled DataSource with Named Configuration and Overrides Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Create a pooled DataSource using the DataSources factory, specifying a named configuration and providing a map of override properties to customize its behavior. ```java // create the PooledDataSource using the a named configuration and specified overrides // "intergalactoApp" is a named configuration ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoApp", overrides ); ``` -------------------------------- ### Initialize c3p0 ComboPooledDataSource with Named Configuration Source: https://context7.com/swaldman/c3p0/llms.txt Initializes a ComboPooledDataSource using a named configuration from c3p0-config.xml. Programmatic overrides can be applied after initialization. ```java import com.mchange.v2.c3p0.*; // Picks up all settings from the "reportingDB" named-config block ComboPooledDataSource reportDs = new ComboPooledDataSource("reportingDB"); // Picks up all settings from the "transactionalDB" named-config block, // then overrides maxPoolSize programmatically ComboPooledDataSource txDs = new ComboPooledDataSource("transactionalDB"); txDs.setMaxPoolSize(60); // runtime override ``` -------------------------------- ### Define Named Configurations (HOCON) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define default and named configurations using HOCON (Human-Optimized Config Object Notation) files. HOCON offers a more structured and flexible configuration format. ```hocon c3p0 { maxPoolSize=30 minPoolSize=10 named-configs { intergalactoApp { maxPoolSize=1000 minPoolSize=100 numHelperThreads=50 } littleTeenyApp { maxPoolSize=5 minPoolSize=2 } } } ``` -------------------------------- ### Run c3p0 JUnit Tests Source: https://github.com/swaldman/c3p0/blob/0.13.x/README.md Execute the JUnit test suite for c3p0. Note that this covers only a small fraction of the library's functionality. ```plaintext $ mill test.test ``` -------------------------------- ### DataSources.unpooledDataSource Overloads Source: https://context7.com/swaldman/c3p0/llms.txt Illustrates the different overloads of DataSources.unpooledDataSource for creating unpooled DataSources. The Properties-based variant allows passing arbitrary driver properties. ```java import com.mchange.v2.c3p0.*; import javax.sql.DataSource; import java.util.Properties; // Overload 1: no arguments — all config from c3p0.properties / System properties DataSource ds1 = DataSources.unpooledDataSource(); // Overload 2: URL only DataSource ds2 = DataSources.unpooledDataSource("jdbc:mysql://localhost/mydb"); // Overload 3: URL + user + password (most common) DataSource ds3 = DataSources.unpooledDataSource( "jdbc:postgresql://localhost/mydb", "alice", "pass"); // Overload 4: URL + arbitrary driver properties (e.g., SSL, socket timeout) Properties driverProps = new Properties(); driverProps.setProperty("user", "alice"); driverProps.setProperty("password", "pass"); driverProps.setProperty("ssl", "true"); driverProps.setProperty("sslmode", "require"); driverProps.setProperty("socketTimeout", "30"); DataSource ds4 = DataSources.unpooledDataSource( "jdbc:postgresql://db.example.com/mydb", driverProps); ``` -------------------------------- ### Run c3p0 Prepared Statement Load Test Source: https://github.com/swaldman/c3p0/blob/0.13.x/README.md This test subjects c3p0 to a continuous load from 100 threads performing database operations using PreparedStatements, effectively exercising the statement cache. ```plaintext $ mill test.c3p0PSLoad ``` -------------------------------- ### Define Per-User Configurations (HOCON) Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Define user-specific overrides for default configurations using HOCON files. This provides a structured way to manage per-user connection pool settings. ```hocon c3p0 { maxPoolSize=30 minPoolSize=10 user-overrides { steve { maxPoolSize=15 minPoolSize=5 } ramona { maxPoolSize=50 minPoolSize=20 } } } ``` -------------------------------- ### Tomcat 5.0 Resource Configuration Source: https://github.com/swaldman/c3p0/blob/0.13.x/doc/docsrc/index.html Configure a c3p0 pooled DataSource for Tomcat 5.0 by adding this fragment to your server.xml's element. Ensure the resource name matches your web.xml declaration. ```xml factory org.apache.naming.factory.BeanFactory driverClass org.postgresql.Driver jdbcUrl jdbc:postgresql://localhost/c3p0-test user swaldman password test minPoolSize 5 maxPoolSize 15 acquireIncrement 5 ``` -------------------------------- ### JNDI Binding and Lookup of c3p0 DataSource Source: https://context7.com/swaldman/c3p0/llms.txt Demonstrates how to bind a c3p0 pooled DataSource to a JNDI name for later lookup. This allows applications to access the DataSource as a plain DataSource object. ```java import com.mchange.v2.c3p0.*; import javax.naming.*; import javax.sql.DataSource; import java.sql.*; public class JndiExample { // Binding side (e.g., in a servlet context listener or startup class) static void bindDataSource(Context ctx) throws Exception { DataSource unpooled = DataSources.unpooledDataSource( "jdbc:postgresql://localhost/mydb", "appuser", "s3cr3t"); DataSource pooled = DataSources.pooledDataSource(unpooled); ctx.rebind("java:comp/env/jdbc/myDB", pooled); System.out.println("DataSource bound to java:comp/env/jdbc/myDB"); } // Consuming side (e.g., in a DAO) static void useDataSource() throws Exception { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDB"); try (Connection con = ds.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO audit_log(event, ts) VALUES (?, now())")) { ps.setString(1, "user_login"); ps.executeUpdate(); System.out.println("Audit entry written."); } } } ```