Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return a connection in c3p0

Tags:

java

c3p0

I am using c3p0 - ComboPooledDataSource. I am initializing once as below.

private void init() {
cpds = new ComboPooledDataSource();
cpds.setDriverClass(driverName);
cpds.setJdbcUrl(url);
cpds.setUser(userName);
cpds.setPassword(pwd);
}

I am getting a connection from the pool as below

public synchronized Connection getLocalConnection(String ipAddr)
    throws SQLException {
return cpds.getConnection();
}

But i am not sure whether its the right way to return the connection back to the pool when i finish executing a query. I guess the

conn.close()

just returns the connection back to the pool instead of REALLY CLOSING the connection. Am i correct or is there any other way around? Pls help.

like image 898
ihavprobs Avatar asked Apr 22 '11 10:04

ihavprobs


People also ask

How does c3p0 connection pool work?

c3p0 is a Java library that provides a convenient way for managing database connections. In short, it achieves this by creating a pool of connections. It also effectively handles the cleanup of Statements and ResultSets after use.

What is c3p0 Hibernate connection pooling?

C3p0 is an open-source JDBC connection pooling library, with support for caching and reuse of PreparedStatements. Hibernate provides support for Java applications to use c3p0 for connection pooling with additional configuration settings.

What is maxConnectionAge?

maxConnectionAge - Integer representing the timeout for the idle DB connection (value of -1 never releases the connection). This property closes connections to the database if a query hasn't been made within the timeout period.

What is acquireIncrement?

acquireIncrement determines how many Connections a c3p0 pool will attempt to acquire when the pool has run out of Connections. (Regardless of acquireIncrement, the pool will never allow maxPoolSize to be exceeded.)


1 Answers

This is initializing code

private DataSource init() {

    DataSource unpooled = DataSources.unpooledDataSource(DB_URL, DB_USERNAME, DB_PASSWORD);

    Map<String, Object> overrideProps = new HashMap<String, Object>();

    overrideProps.put("maxPoolSize", MAX_POOL_SIZE);
    overrideProps.put("minPoolSize", MIN_POOL_SIZE);

    return DataSources.pooledDataSource(unpooled, overrideProps);
}

And you get connection from DataSource.

public Connection getConnection() throws SQLException {
    return dataSource.getConnection();
}

And to close the connection just call close() method.

connection.close();
like image 55
user179437 Avatar answered Sep 24 '22 21:09

user179437