Example usage for org.apache.commons.dbcp BasicDataSource BasicDataSource

List of usage examples for org.apache.commons.dbcp BasicDataSource BasicDataSource

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource BasicDataSource.

Prototype

BasicDataSource

Source Link

Usage

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java

/** Initialize the connection pool */
public void connect() {
    try {//from  w w  w .  j a  v  a  2 s.co m
        ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUsername(dbUser);
        ds.setPassword(dbPassword);
        ds.setUrl(dbURL);
        //ds.setUrl("jdbc:mysql://localhost:3306/jmarkets");
        ds.setMaxActive(this.maxNumConn);
        ds.setDefaultAutoCommit(this.autoCommit);
        ds.setDefaultReadOnly(this.readOnly);

        //conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?user=" + dbUser + "&password=" + dbPassword);
        //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jmarkets2?user=root&password=");//?user=blah&password=blah");
        log.info("Successfully connected to the jMarkets database");

    } catch (Exception e) {
        log.fatal("Failed to connect to the jMarkets database: " + e);
    }
}

From source file:com.alibaba.otter.manager.biz.common.DataSourceCreator.java

private DataSource createDataSource(String url, String userName, String password, String driverClassName,
        DataMediaType dataMediaType, String encoding) {
    BasicDataSource dbcpDs = new BasicDataSource();

    dbcpDs.setInitialSize(initialSize);// ?
    dbcpDs.setMaxActive(maxActive);// ?????
    dbcpDs.setMaxIdle(maxIdle);// ??
    dbcpDs.setMinIdle(minIdle);// ?0?
    dbcpDs.setMaxWait(maxWait);// ??-1?
    dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout
    dbcpDs.setLogAbandoned(true);// ??
    dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ?
    dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ??
    dbcpDs.setTestOnBorrow(false);// ??
    dbcpDs.setTestOnReturn(false);// ??
    dbcpDs.setTestWhileIdle(true);// ????
    dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ????????
    dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ???????

    // ??/*from   w w  w  .j  a  va 2 s  . co  m*/
    dbcpDs.setDriverClassName(driverClassName);
    dbcpDs.setUrl(url);
    dbcpDs.setUsername(userName);
    dbcpDs.setPassword(password);

    if (dataMediaType.isOracle()) {
        dbcpDs.addConnectionProperty("restrictGetTables", "true");
        // dbcpDs.setValidationQuery("select 1 from dual");
    } else if (dataMediaType.isMysql()) {
        // open the batch mode for mysql since 5.1.8
        dbcpDs.addConnectionProperty("useServerPrepStmts", "false");
        dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true");
        dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null
        dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date?
        dbcpDs.addConnectionProperty("noDatetimeStringSync", "true");// ,???
        if (StringUtils.isNotEmpty(encoding)) {
            if (StringUtils.equalsIgnoreCase(encoding, "utf8mb4")) {
                dbcpDs.addConnectionProperty("characterEncoding", "utf8");
                dbcpDs.setConnectionInitSqls(Arrays.asList("set names utf8mb4"));
            } else {
                dbcpDs.addConnectionProperty("characterEncoding", encoding);
            }
        }
        // dbcpDs.setValidationQuery("select 1");
    } else {
        logger.error("ERROR ## Unknow database type");
    }

    return dbcpDs;
}

From source file:com.dangdang.ddframe.rdb.sharding.example.transaction.Main.java

private static DataSource createTransactionLogDataSource() {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
    result.setUrl("jdbc:mysql://localhost:3306/trans_log");
    result.setUsername("root");
    result.setPassword("");
    return result;
}

From source file:com.dangdang.ddframe.rdb.sharding.config.yaml.YamlintegratedTest.java

@Test(expected = IllegalArgumentException.class)
public void testBindingError() {
    Yaml yaml = new Yaml(new Constructor(ShardingRuleConfig.class));
    Map<String, DataSource> dsMap = new HashMap<>();
    dsMap.put("ds", new BasicDataSource());
    ShardingRuleConfig config = (ShardingRuleConfig) yaml
            .load(YamlintegratedTest.class.getResourceAsStream("/config/config-bindingError.yaml"));
    ShardingRule shardingRule = new ShardingRuleBuilder("config-bindingError.yaml", dsMap, config).build();
    for (TableRule tableRule : shardingRule.getBindingTableRules().iterator().next().getTableRules()) {
        log.info(tableRule.toString());/*from  ww w . jav  a2s . co  m*/
    }
}

From source file:com.alibaba.otter.common.push.datasource.media.MediaPushDataSource.java

protected DataSource doCreateDataSource(String url) {
    BasicDataSource dbcpDs = new BasicDataSource();

    dbcpDs.setInitialSize(initialSize);// ?
    dbcpDs.setMaxActive(maxActive);// ?????
    dbcpDs.setMaxIdle(maxIdle);// ??
    dbcpDs.setMinIdle(minIdle);// ?0?
    dbcpDs.setMaxWait(maxWait);// ??-1?
    dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout
    dbcpDs.setLogAbandoned(true);// ??
    dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ?
    dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ??
    dbcpDs.setTestOnBorrow(false);// ??
    dbcpDs.setTestOnReturn(false);// ??
    dbcpDs.setTestWhileIdle(true);// ????
    dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ????????
    dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ???????

    // ??//from w w  w  .  j  a v a  2 s.c  o m
    dbcpDs.setDriverClassName(driverClassName);
    dbcpDs.setUrl(url);
    dbcpDs.setUsername(userName);
    dbcpDs.setPassword(password);

    if (dataMediaType.isOracle()) {
        dbcpDs.addConnectionProperty("restrictGetTables", "true");
        dbcpDs.setValidationQuery("select 1 from dual");
    } else if (dataMediaType.isMysql()) {
        // open the batch mode for mysql since 5.1.8
        dbcpDs.addConnectionProperty("useServerPrepStmts", "false");
        dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true");
        dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null
        dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date?
        if (StringUtils.isNotEmpty(encoding)) {
            dbcpDs.addConnectionProperty("characterEncoding", encoding);
        }
        dbcpDs.setValidationQuery("select 1");
    } else {
        logger.error("ERROR ## Unknow database type");
    }

    return dbcpDs;
}

From source file:edu.ucsf.vitro.opensocial.OpenSocialSmokeTests.java

/**
 * Check that we can connect to the database, and query one of the Shindig
 * tables./*from   ww w .  java  2  s .c o  m*/
 */
private void checkDatabaseTables() {
    BasicDataSource dataSource = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(getProperty(PROPERTY_DB_DRIVER));
        dataSource.setUrl(getProperty(PROPERTY_DB_JDBC_URL));
        dataSource.setUsername(getProperty(PROPERTY_DB_USERNAME));
        dataSource.setPassword(getProperty(PROPERTY_DB_PASSWORD));

        conn = dataSource.getConnection();
        stmt = conn.createStatement();
        rset = stmt.executeQuery("select * from orng_apps");
    } catch (NoSuchPropertyException e) {
        warnings.add(new Warning(e.getMessage()));
    } catch (SQLException e) {
        if (e.getMessage().contains("doesn't exist")) {
            warnings.add(new Warning("The Shindig tables don't exist "
                    + "in the database. Was shindig_orng_tables.sql " + "run to set them up?", e));
        } else {
            warnings.add(new Warning("Can't access the Shindig database tables", e));
        }
    } finally {
        try {
            if (rset != null) {
                rset.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.dangdang.ddframe.rdb.sharding.example.jdbc.Main.java

private static DataSource createDataSource(final String dataSourceName) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
    result.setUrl(String.format("jdbc:mysql://localhost:3306/%s", dataSourceName));
    result.setUsername("root");
    result.setPassword("");
    return result;
}

From source file:com.alibaba.druid.benckmark.pool.Case3.java

public void dbcp() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();

    dataSource.setInitialSize(initialSize);
    dataSource.setMaxActive(maxActive);//from www  .java 2  s. co m
    dataSource.setMaxIdle(maxIdle);
    dataSource.setMaxWait(maxWait);
    dataSource.setMinIdle(minIdle);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(jdbcUrl);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setValidationQuery(validationQuery);
    dataSource.setTestOnBorrow(testOnBorrow);
    dataSource.setConnectionProperties(connectionProperties);
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    for (int i = 0; i < TEST_COUNT; ++i) {
        p0(dataSource, "dbcp", threadCount);
    }
    // dataSource.close();
    System.out.println();
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsSQLDataSourceFactory.java

/**
 * Setup a dataSource for "users". Usage is for all users for consultation functions.
 * //from ww  w. ja  v  a2s .c  o m
 * @param dataSource
 *          the DataSource to update
 * @return SitoolsDataSource the new DataSource
 */
public SitoolsSQLDataSource setupDataSourceForUsers(JDBCDataSource dataSource) {
    String key = dataSource.getId();
    SitoolsSQLDataSource foundDatasource = dataSources.get(key);
    if (foundDatasource == null) {

        BasicDataSource ds = new BasicDataSource();
        // OSGi
        ds.setDriverClassLoader(getClass().getClassLoader());
        ds.setDriverClassName(dataSource.getDriverClass());
        ds.setUsername(dataSource.getUserLogin());
        ds.setPassword(dataSource.getUserPassword());
        ds.setUrl(dataSource.getUrl());
        ds.setMaxActive(dataSource.getMaxActive());
        ds.setInitialSize(dataSource.getInitialSize());
        ds.setDefaultReadOnly(true);
        // test that the connection is alive on each request. If not It will be dropped from the pool and another
        // connection will be created
        ds.setTestOnBorrow(true);
        ds.setValidationQuery("SELECT 1");
        if ((dataSource.getSchemaOnConnection() != null) && !dataSource.getSchemaOnConnection().equals("")) {
            ds.setDefaultCatalog(dataSource.getSchemaOnConnection());
        }
        foundDatasource = new SitoolsSQLDataSource(dataSource, ds, dataSource.getSchemaOnConnection());
        dataSources.put(key, foundDatasource);
    }
    return foundDatasource;
}

From source file:com.alibaba.druid.benckmark.pool.Case1.java

public void test_dbcp() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();

    dataSource.setInitialSize(initialSize);
    dataSource.setMaxActive(maxActive);/*from w  ww.  j av a  2  s.  c om*/
    dataSource.setMinIdle(minPoolSize);
    dataSource.setMaxIdle(maxPoolSize);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(jdbcUrl);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(false);

    for (int i = 0; i < loopCount; ++i) {
        p0(dataSource, "dbcp", threadCount);
    }
    System.out.println();
}