Java Code Examples for com.mchange.v2.c3p0.ComboPooledDataSource#setUser()

The following examples show how to use com.mchange.v2.c3p0.ComboPooledDataSource#setUser() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: C3P0Factory.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static DataSource createDataSourceFor(JdbcClient jdbc) {
	ComboPooledDataSource pool = new ComboPooledDataSource();

	pool.setJdbcUrl(jdbc.url());
	pool.setUser(jdbc.username());
	pool.setPassword(jdbc.password());

	try {
		pool.setDriverClass(jdbc.driver());
	} catch (PropertyVetoException e) {
		throw U.rte("Cannot load JDBC driver!", e);
	}

	Conf.section("c3p0").applyTo(pool);

	return pool;
}
 
Example 2
Source File: C3P0ConnectionPool.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
 * 使用硬连接的方式
 * @throws PropertyVetoException
 * @throws SQLException
 */
public void HardcodeStyleTest() throws PropertyVetoException, SQLException {
    // 1.创建连接池的核心工具类
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    // 2.设置连接数据库所需的参数
    comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
    comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day34jdbc?serverTimezone = GMT%2B8 ");
    comboPooledDataSource.setUser("root");
    comboPooledDataSource.setPassword("GJXAIOU");

    // 3.设置C3P0连接池的属性:初始化连接数、最大连接数、等待时间
    comboPooledDataSource.setInitialPoolSize(3);
    comboPooledDataSource.setMaxPoolSize(6);
    comboPooledDataSource.setMaxIdleTime(1000);

    // 4.从连接池中获取数据库连接对象
    Connection connection = comboPooledDataSource.getConnection();

    // 5.准备preparedStatement执行SQL语句
    connection.prepareStatement("delete from person where id = 3").executeUpdate();
}
 
Example 3
Source File: C3P0DataSourceProvider.java    From minnal with Apache License 2.0 6 votes vote down vote up
protected PooledDataSource createDataSource() {
	logger.info("Creating the data source with the configuration {}", configuration);
	if (configuration == null) {
		logger.error("Database configuration is not set");
		throw new MinnalException("Database configuration is not set");
	}
	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	try {
		Class.forName(configuration.getDriverClass());
		dataSource.setJdbcUrl(configuration.getUrl());
		dataSource.setUser(configuration.getUsername());
		dataSource.setPassword(configuration.getPassword());
		dataSource.setIdleConnectionTestPeriod(configuration.getIdleConnectionTestPeriod());
		dataSource.setInitialPoolSize(configuration.getMinSize());
		dataSource.setMaxPoolSize(configuration.getMaxSize());
	} catch (Exception e) {
		logger.error("Failed while creating the data source", e);
		throw new MinnalException("Failed while configuring the data source", e);
	}
	return dataSource;
}
 
Example 4
Source File: C3P0DataSource.java    From maven-framework-project with MIT License 6 votes vote down vote up
private C3P0DataSource() throws IOException, SQLException,
		PropertyVetoException {
	cpds = new ComboPooledDataSource();
	cpds.setDriverClass("org.h2.Driver"); // loads the jdbc driver
	cpds.setJdbcUrl("jdbc:h2:./target/test;AUTO_SERVER=TRUE");
	cpds.setUser("sa");
	cpds.setPassword("");

	// the settings below are optional -- c3p0 can work with defaults
	cpds.setMinPoolSize(5);
	cpds.setAcquireIncrement(5);
	cpds.setMaxPoolSize(20);
	cpds.setMaxStatements(180);

	this.setDataSource(cpds);

}
 
Example 5
Source File: DatasourceConfig.java    From libevent with Apache License 2.0 6 votes vote down vote up
@Bean
@Primary
public DataSource dataSource() throws PropertyVetoException {
    ComboPooledDataSource rlt = new ComboPooledDataSource();
    rlt.setDriverClass("com.mysql.jdbc.Driver");
    rlt.setUser("root");
    rlt.setPassword("password");
    rlt.setJdbcUrl("jdbc:mysql://localhost:3306/libevent_sample");
    rlt.setInitialPoolSize(DEFAULT_POOL_SIZE);
    rlt.setMaxPoolSize(DEFAULT_POOL_SIZE);
    rlt.setMinPoolSize(DEFAULT_POOL_SIZE);
    rlt.setTestConnectionOnCheckin(true);
    rlt.setPreferredTestQuery("select 1");

    return rlt;
}
 
Example 6
Source File: CreateC3p0Connection.java    From spiracle with Apache License 2.0 5 votes vote down vote up
private ComboPooledDataSource createConnectionPool() throws PropertyVetoException {
	ComboPooledDataSource ds = new ComboPooledDataSource();

	ds.setDriverClass(jdbcDriver);
	ds.setJdbcUrl(url);
	ds.setUser(username);
	ds.setPassword(password);
	ds.setMinPoolSize(5);
	ds.setAcquireIncrement(5);
	ds.setMaxPoolSize(maxPoolSize);

	return ds;
}
 
Example 7
Source File: DAOFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
protected DAOFactory(String facName, String driverClassName, String jdbcURL, String userName, String userPassword,
        int initPoolSize, int MinPoolSize, int MaxPoolSize, int maxIdleTime, int idleConnectionTestPeriod,
        String testQuerySQL) {

    this.facName = facName;

    ds = new ComboPooledDataSource();
    // 设置JDBC的Driver类
    try {
        ds.setDriverClass(driverClassName);
    }
    catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }
    // 设置JDBC的URL
    ds.setJdbcUrl(jdbcURL);
    // 设置数据库的登录用户名
    ds.setUser(userName);
    // 设置数据库的登录用户密码
    ds.setPassword(userPassword);
    // 设置连接池的最大连接数
    ds.setMaxPoolSize(MaxPoolSize);
    // 设置连接池的最小连接数
    ds.setMinPoolSize(MinPoolSize);
    // 设置初始化连接数
    ds.setInitialPoolSize(initPoolSize);
    // 设置最大闲置时间
    ds.setMaxIdleTime(maxIdleTime);
    // 设置测试SQL
    ds.setPreferredTestQuery(testQuerySQL);
    // 设置闲置测试周期
    ds.setIdleConnectionTestPeriod(idleConnectionTestPeriod);
    // 增加单个连接的Statements数量
    ds.setMaxStatements(0);
    // 连接池内单个连接所拥有的最大缓存statements数
    ds.setMaxStatementsPerConnection(200);
    // 获取空闲连接超时时间
    ds.setCheckoutTimeout(10 * 1000);
}
 
Example 8
Source File: MysqlHelper.java    From WebCollector with GNU General Public License v3.0 5 votes vote down vote up
public DataSource createDataSource(String url, String username, String password, int initialSize, int maxPoolSize) throws PropertyVetoException {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl(url);
    dataSource.setUser(username);
    dataSource.setPassword(password);
    dataSource.setInitialPoolSize(initialSize);
    dataSource.setMaxPoolSize(maxPoolSize);
    dataSource.setTestConnectionOnCheckout(true);
    return dataSource;
}
 
Example 9
Source File: Database.java    From SQLite-sync.com with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Database() {

        String version = "";
        try {
            String resourceName = "project.properties";
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Properties props = new Properties();
            try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
                props.load(resourceStream);
            }
            version = props.getProperty("version");
        } catch (IOException ex){
            Logs.write(Logs.Level.ERROR, "GetVersionOfSQLiteSyncCOM: " + ex.getMessage());
        }
        SQLiteSyncVersion = version;

        SQLiteSyncConfig.Load();

        try {
            cpds = new ComboPooledDataSource();
            cpds.setDriverClass(SQLiteSyncConfig.DBDRIVER); //loads the jdbc driver
            cpds.setJdbcUrl(SQLiteSyncConfig.DBURL);
            cpds.setUser(SQLiteSyncConfig.DBUSER);
            cpds.setPassword(SQLiteSyncConfig.DBPASS);

            // the settings below are optional -- c3p0 can work with defaults
            cpds.setMinPoolSize(3);
            cpds.setAcquireIncrement(3);
            cpds.setMaxPoolSize(10);
            cpds.setIdleConnectionTestPeriod(300);
            cpds.setMaxIdleTime(240);
            cpds.setTestConnectionOnCheckin(false);
            cpds.setMaxStatements(2000);
            cpds.setMaxStatementsPerConnection(100);

        } catch (PropertyVetoException e){
            Logs.write(Logs.Level.ERROR, "Database constructor: " + e.getMessage());
        }
    }
 
Example 10
Source File: OrderServiceApplication.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
@Bean
@Profile("db")
public DataSource tccDataSource() throws Exception {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/TCC?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false");
    dataSource.setUser("root");
    dataSource.setPassword("admin");
    return dataSource;
}
 
Example 11
Source File: C3P0PoolSlaveManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveDBUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("openzaly init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 12
Source File: ConnectionPoolManager.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
private DataSource createDataSource(String driverClass, String url, String account, String password) {
	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	try {
		dataSource.setDriverClass(driverClass);
		dataSource.setJdbcUrl(url);
		dataSource.setUser(account);
		dataSource.setPassword(password);

		dataSource.setMinPoolSize(10);
		dataSource.setMaxPoolSize(35);
		dataSource.setAcquireIncrement(0);
		dataSource.setMaxStatements(0);
		
		/** 最大允許的閒置時間(秒) */
		dataSource.setMaxIdleTime(300);
		/** 對閒置的連線進行Query測試設置(秒) */
		dataSource.setIdleConnectionTestPeriod(1800);
		
		/** Checkin connection時不檢查連線是否有效 */
		dataSource.setTestConnectionOnCheckin(false);
		/** Checkout connection時檢查連線的有效性*/
		dataSource.setTestConnectionOnCheckout(true);
		/** 進行test時使用的 Query設定*/
		dataSource.setPreferredTestQuery("SELECT 1;");
		/** Connection的最大有效時數(秒)*/
		dataSource.setMaxConnectionAge(28800);
		/** Connection checkout 之後的有效時數(毫秒)*/
		dataSource.setCheckoutTimeout(28800000);
	} catch (PropertyVetoException e) {
		e.printStackTrace();
	}
	mPoolMap.put(url, dataSource);
	return dataSource;
}
 
Example 13
Source File: C3p0ConnectionService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * {@inheritDoc }
 */
@Override
public void init( Map<String, String> htParamsConnectionPool )
{
    try
    {
        _dataSource = new ComboPooledDataSource( _strPoolName );

        String strDriver = htParamsConnectionPool.get( getPoolName( ) + ".driver" );
        _dataSource.setDriverClass( strDriver );

        String strUrl = htParamsConnectionPool.get( getPoolName( ) + ".url" );
        strUrl = EnvUtil.evaluate( strUrl, EnvUtil.PREFIX_ENV );
        _dataSource.setJdbcUrl( strUrl );

        String strUser = htParamsConnectionPool.get( getPoolName( ) + ".user" );
        strUser = EnvUtil.evaluate( strUser, EnvUtil.PREFIX_ENV );
        _dataSource.setUser( strUser );

        String strPassword = htParamsConnectionPool.get( getPoolName( ) + ".password" );
        strPassword = EnvUtil.evaluate( strPassword, EnvUtil.PREFIX_ENV );
        _dataSource.setPassword( strPassword );

        String strMaxConns = htParamsConnectionPool.get( getPoolName( ) + ".maxconns" );
        int nMaxConns = ( strMaxConns == null ) ? 0 : Integer.parseInt( strMaxConns );
        _dataSource.setMaxPoolSize( nMaxConns );

        String strMinConns = htParamsConnectionPool.get( getPoolName( ) + ".initconns" );
        int nInitConns = ( strMinConns == null ) ? 0 : Integer.parseInt( strMinConns );
        _dataSource.setInitialPoolSize( nInitConns );
        _dataSource.setMinPoolSize( nInitConns );
    }
    catch( Exception e )
    {
        _logger.error( "Error while initializing the pool " + getPoolName( ), e );
    }

    _logger.info( "Initialization of the C3P0 pool named '" + getPoolName( ) + "', Min/Max pool size : " + _dataSource.getMinPoolSize( ) + "/"
            + _dataSource.getMaxPoolSize( ) );
}
 
Example 14
Source File: MainConfigofProfile.java    From code with Apache License 2.0 5 votes vote down vote up
@Profile("dev")
@Bean("devDataSource")
public DataSource dataSourceDev(@Value("${db.password}") String pwd) throws PropertyVetoException {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setUser(user);
    dataSource.setPassword(pwd);
    dataSource.setDriverClass(driverClass);
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");
    return dataSource;
}
 
Example 15
Source File: MainConfigofProfile.java    From code with Apache License 2.0 5 votes vote down vote up
@Profile("test")
@Bean("testDataSource")
public DataSource dataSourceTest(@Value("${db.password}") String pwd) throws PropertyVetoException {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setUser(user);
    dataSource.setPassword(pwd);
    dataSource.setDriverClass(driverClass);
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    return dataSource;
}
 
Example 16
Source File: CompareWithPopularPool.java    From clearpool with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testC3p0() throws Exception {
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  dataSource.setMinPoolSize(this.corePoolSize);
  dataSource.setMaxPoolSize(this.maxPoolSize);
  dataSource.setDriverClass(this.driverClassName);
  dataSource.setJdbcUrl(this.url);
  dataSource.setUser(this.username);
  dataSource.setPassword(this.password);
  for (int i = 0; i < this.loop; ++i) {
    ThreadProcessUtils.process(dataSource, "c3p0", this.count, threadCount, physicalCon);
  }
  System.out.println();
}
 
Example 17
Source File: DefaultDataSourceManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private List<DataSource> getReadOnlyDataSources()
{
    String mainUser = config.getProperty( ConfigurationKey.CONNECTION_USERNAME );
    String mainPassword = config.getProperty( ConfigurationKey.CONNECTION_PASSWORD );
    String driverClass = config.getProperty( CONNECTION_DRIVER_CLASS );
    String maxPoolSize = config.getPropertyOrDefault( CONNECTION_POOL_MAX_SIZE, DEFAULT_POOL_SIZE );

    Properties props = config.getProperties();

    List<DataSource> dataSources = new ArrayList<>();

    for ( int i = 1; i <= MAX_READ_REPLICAS; i++ )
    {
        String jdbcUrl = props.getProperty( String.format( FORMAT_CONNECTION_URL, i ) );
        String user = props.getProperty( String.format( FORMAT_CONNECTION_USERNAME, i ) );
        String password = props.getProperty( String.format( FORMAT_CONNECTION_PASSWORD, i ) );

        user = StringUtils.defaultIfEmpty( user, mainUser );
        password = StringUtils.defaultIfEmpty( password, mainPassword );

        if ( ObjectUtils.allNonNull( jdbcUrl, user, password ) )
        {
            try
            {
                ComboPooledDataSource ds = new ComboPooledDataSource();

                ds.setDriverClass( driverClass );
                ds.setJdbcUrl( jdbcUrl );
                ds.setUser( user );
                ds.setPassword( password );
                ds.setMaxPoolSize( Integer.parseInt( maxPoolSize ) );
                ds.setAcquireIncrement( VAL_ACQUIRE_INCREMENT );
                ds.setMaxIdleTime( VAL_MAX_IDLE_TIME );

                dataSources.add( ds );

                log.info( String.format( "Found read replica, index: '%d', connection URL: '%s''", i, jdbcUrl ) );

                testConnection( ds );
            }
            catch ( PropertyVetoException ex )
            {
                throw new IllegalArgumentException( "Invalid configuration of read replica: " + jdbcUrl, ex );
            }
        }
    }

    log.info( "Read only configuration initialized, read replicas found: " + dataSources.size() );

    return dataSources;
}
 
Example 18
Source File: H2Db.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public boolean open( String dbPath ) throws Exception {
    this.mDbPath = dbPath;

    connectionData = new ConnectionData();
    connectionData.connectionLabel = dbPath;
    connectionData.connectionUrl = new String(dbPath);
    connectionData.user = user;
    connectionData.password = password;
    connectionData.dbType = getType().getCode();

    boolean dbExists = false;
    if (dbPath != null) {
        File dbFile = new File(dbPath + "." + EDb.H2.getExtension());
        if (dbFile.exists()) {
            if (mPrintInfos)
                Logger.INSTANCE.insertInfo(null, "Database exists");
            dbExists = true;
        }
        if (dbPath.toLowerCase().startsWith("tcp")) {
            // no way to check, assume it exists
            dbExists = true;

            // also cleanup path
            int first = dbPath.indexOf('/');
            int second = dbPath.indexOf('/', first + 1);
            int third = dbPath.indexOf('/', second + 1);
            int lastSlash = dbPath.indexOf('/', third + 1);
            if (lastSlash != -1) {
                mDbPath = dbPath.substring(lastSlash, dbPath.length());
            }
        }
    } else {
        dbPath = "mem:syntax";
        dbExists = false;
    }

    String jdbcUrl = EDb.H2.getJdbcPrefix() + dbPath;

    if (makePooled) {
        Properties p = new Properties(System.getProperties());
        p.put("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog");
        p.put("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF");
        System.setProperties(p);

        comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(DRIVER_CLASS);
        comboPooledDataSource.setJdbcUrl(jdbcUrl);
        if (user != null && password != null) {
            comboPooledDataSource.setUser(user);
            comboPooledDataSource.setPassword(password);
        }
        comboPooledDataSource.setInitialPoolSize(10);
        comboPooledDataSource.setMinPoolSize(5);
        comboPooledDataSource.setAcquireIncrement(5);
        comboPooledDataSource.setMaxPoolSize(30);
        comboPooledDataSource.setMaxStatements(100);
        comboPooledDataSource.setMaxIdleTime(14400); // 4 hours by default

        // comboPooledDataSource.setCheckoutTimeout(2000);
        comboPooledDataSource.setAcquireRetryAttempts(1);
        // comboPooledDataSource.setBreakAfterAcquireFailure(false);
        // TODO remove after debug
        // comboPooledDataSource.setUnreturnedConnectionTimeout(180);

    } else {
        if (user != null && password != null) {
            singleJdbcConn = DriverManager.getConnection(jdbcUrl, user, password);
        } else {
            singleJdbcConn = DriverManager.getConnection(jdbcUrl);
        }
    }
    if (mPrintInfos) {
        String[] dbInfo = getDbInfo();
        Logger.INSTANCE.insertDebug(null, "H2 Version: " + dbInfo[0] + "(" + dbPath + ")");
    }
    return dbExists;
}
 
Example 19
Source File: PGDb.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public boolean open( String dbPath ) throws Exception {
        this.mDbPath = dbPath;

        connectionData = new ConnectionData();
        connectionData.connectionLabel = dbPath;
        connectionData.connectionUrl = new String(dbPath);
        connectionData.user = user;
        connectionData.password = password;
        connectionData.dbType = getType().getCode();

        boolean dbExists = true;

        String jdbcUrl = EDb.POSTGRES.getJdbcPrefix() + dbPath;

        if (makePooled) {
            Properties p = new Properties(System.getProperties());
            p.put("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog");
            p.put("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF"); // Off or any
                                                                                  // other level
            System.setProperties(p);

//            testConnectionOnCheckin validates the connection when it is returned to the pool. 
//            idleConnectionTestPeriod sets a limit to how long a connection will stay idle before testing it.
//            maxIdleTimeExcessConnections will bring back the connectionCount back down to minPoolSize after a spike in activity.

            comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass(DRIVER_CLASS);
            comboPooledDataSource.setJdbcUrl(jdbcUrl);
            if (user != null && password != null) {
                comboPooledDataSource.setUser(user);
                comboPooledDataSource.setPassword(password);
            }
            comboPooledDataSource.setMinPoolSize(5);
            comboPooledDataSource.setMaxPoolSize(30);
            comboPooledDataSource.setAcquireIncrement(1);
            comboPooledDataSource.setInitialPoolSize(10);
            comboPooledDataSource.setMaxStatements(100);
            comboPooledDataSource.setTestConnectionOnCheckin(true);
            comboPooledDataSource.setIdleConnectionTestPeriod(300);
            comboPooledDataSource.setMaxIdleTimeExcessConnections(240);

            // comboPooledDataSource.setCheckoutTimeout(2000);
            comboPooledDataSource.setAcquireRetryAttempts(1);
            // comboPooledDataSource.setBreakAfterAcquireFailure(false);
            // TODO remove after debug
            // comboPooledDataSource.setUnreturnedConnectionTimeout(180);

        } else {
            if (user != null && password != null) {
                singleJdbcConn = DriverManager.getConnection(jdbcUrl, user, password);
            } else {
                singleJdbcConn = DriverManager.getConnection(jdbcUrl);
            }
        }
        if (mPrintInfos) {
            String[] dbInfo = getDbInfo();
            Logger.INSTANCE.insertDebug(null, "Postgresql Version: " + dbInfo[0] + "(" + dbPath + ")");
        }
        return dbExists;
    }
 
Example 20
Source File: L2DatabaseFactory.java    From L2jBrasil with GNU General Public License v3.0 4 votes vote down vote up
public L2DatabaseFactory() throws SQLException
{
	try
	{
		if (Config.DATABASE_MAX_CONNECTIONS < 2)
           {
               Config.DATABASE_MAX_CONNECTIONS = 2;
               _log.warning("at least " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
           }

		_source = new ComboPooledDataSource();
		_source.setAutoCommitOnClose(true);

		_source.setInitialPoolSize(10);
		_source.setMinPoolSize(10);
		_source.setMaxPoolSize(Config.DATABASE_MAX_CONNECTIONS);

		_source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
		_source.setAcquireRetryDelay(500);  // 500 miliseconds wait before try to acquire connection again
		_source.setCheckoutTimeout(0);      // 0 = wait indefinitely for new connection
		// if pool is exhausted
		_source.setAcquireIncrement(5);     // if pool is exhausted, get 5 more connections at a time
		// cause there is a "long" delay on acquire connection
		// so taking more than one connection at once will make connection pooling
		// more effective.

		// this "connection_test_table" is automatically created if not already there
		_source.setAutomaticTestTable("connection_test_table");
		_source.setTestConnectionOnCheckin(false);

		// testing OnCheckin used with IdleConnectionTestPeriod is faster than  testing on checkout

		_source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
		_source.setMaxIdleTime(0); // 0 = idle connections never expire
		// *THANKS* to connection testing configured above
		// but I prefer to disconnect all connections not used
		// for more than 1 hour

		// enables statement caching,  there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
		_source.setMaxStatementsPerConnection(100);

		_source.setBreakAfterAcquireFailure(false);  // never fail if any way possible
		// setting this to true will make
		// c3p0 "crash" and refuse to work
		// till restart thus making acquire
		// errors "FATAL" ... we don't want that
		// it should be possible to recover
		_source.setDriverClass(Config.DATABASE_DRIVER);
		_source.setJdbcUrl(Config.DATABASE_URL);
		_source.setUser(Config.DATABASE_LOGIN);
		_source.setPassword(Config.DATABASE_PASSWORD);

		/* Test the connection */
		_source.getConnection().close();

		if (Config.DEBUG) _log.fine("Database Connection Working");

		if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
               _providerType = ProviderType.MsSql;
           else
               _providerType = ProviderType.MySql;
	}
	catch (SQLException x)
	{
		if (Config.DEBUG) _log.fine("Database Connection FAILED");
		// rethrow the exception
		throw x;
	}
	catch (Exception e)
	{
		if (Config.DEBUG) _log.fine("Database Connection FAILED");
		throw new SQLException("could not init DB connection:"+e);
	}
}