Java中使用C3P0连接池

[b]1、c3p0.properties[/b]
c3p0.driverClass=org.postgresql.Driver
c3p0.jdbcUrl=jdbc:postgresql://192.168.20.33:5432/kwtmap
c3p0.user=nwd
c3p0.password=ok123456
c3p0.minPoolSize=5
c3p0.maxPoolSize=20
c3p0.acquireIncrement=5
c3p0.initialPoolSize=5
c3p0.maxIdleTime=240
[b]2、Java代码[/b]
package com.boonya.mongo.optimize;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.boonya.mongo.utils.ConstantUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* MDBManager.java
* 功能:使用C3P0连接池获取数据库连接对象
* @author boonya
* @version 1.0 2013-03-07
*/
public class MDBManager {

private static final MDBManager instance=new MDBManager();
private static ComboPooledDataSource cpds=new ComboPooledDataSource(true);

/**
* 此处可以不配置,采用默认也行
*/
static{
cpds.setDataSourceName("mydatasource");
cpds.setJdbcUrl(ConstantUtils.getValue("c3p0.jdbcUrl").toString());
try {
cpds.setDriverClass(ConstantUtils.getValue("c3p0.driverClass").toString());
} catch (PropertyVetoException e) {
e.printStackTrace();
}
cpds.setUser(ConstantUtils.getValue("c3p0.user").toString());
cpds.setPassword(ConstantUtils.getValue("c3p0.password").toString());
cpds.setMaxPoolSize(Integer.valueOf(ConstantUtils.getValue("c3p0.maxPoolSize").toString()));
cpds.setMinPoolSize(Integer.valueOf(ConstantUtils.getValue("c3p0.minPoolSize").toString()));
cpds.setAcquireIncrement(Integer.valueOf(ConstantUtils.getValue("c3p0.acquireIncrement").toString()));
cpds.setInitialPoolSize(Integer.valueOf(ConstantUtils.getValue("c3p0.initialPoolSize").toString()));
cpds.setMaxIdleTime(Integer.valueOf(ConstantUtils.getValue("c3p0.maxIdleTime").toString()));
}

private MDBManager(){}

public static MDBManager getInstance(){
return instance;
}

public static Connection getConnection(){
try {
return cpds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

}

你可能感兴趣的:(Java-Basic,C3P0,java)