Java Code Examples for com.alibaba.druid.pool.DruidDataSource#setPassword()

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#setPassword() . 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: DruidDataSourceConfig.java    From easyweb with Apache License 2.0 6 votes vote down vote up
@Bean(name = "mysqlDataSource")
@Primary
public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(databaseConfig.getUrl());
    datasource.setDriverClassName(databaseConfig.getDriverClassName());
    datasource.setUsername(databaseConfig.getUsername());
    datasource.setPassword(databaseConfig.getPassword());
    datasource.setInitialSize(databaseConfig.getInitialSize());
    datasource.setMinIdle(databaseConfig.getMinIdle());
    datasource.setMaxWait(databaseConfig.getMaxWait());
    datasource.setMaxActive(databaseConfig.getMaxActive());
    datasource.setMinEvictableIdleTimeMillis(databaseConfig.getMinEvictableIdleTimeMillis());
    try {
        datasource.setFilters("stat,wall,log4j2");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return datasource;
}
 
Example 2
Source File: JDBCTransactionStore.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
@Override
public boolean load() {
    try {
        druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(messageStoreConfig.getJdbcDriverClass());
        druidDataSource.setUrl(messageStoreConfig.getJdbcURL());
        druidDataSource.setUsername(messageStoreConfig.getJdbcUser());
        druidDataSource.setPassword(messageStoreConfig.getJdbcPassword());
        druidDataSource.setInitialSize(5);
        druidDataSource.setMaxActive(10);
        druidDataSource.setMinIdle(5);
        druidDataSource.setMaxWait(2000);
        druidDataSource.setMinEvictableIdleTimeMillis(300000);
        druidDataSource.setUseUnfairLock(true);
        druidDataSource.setConnectionErrorRetryAttempts(3);
        druidDataSource.setValidationQuery("SELECT 'x'");
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.init();
        return true;
    } catch (Exception e) {
        log.info("druidDataSource load Exeption", e);
        return false;
    }
}
 
Example 3
Source File: DynamicDataSource.java    From galaxy with Apache License 2.0 6 votes vote down vote up
private DataSource getDruidDataSource(DataSourceInfoDto dto) {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(dto.getDbUrl());
    druidDataSource.setUsername(dto.getUsername());
    druidDataSource.setPassword(getPassword(dto.getUsername(), dto.getPassword()));
    druidDataSource.setMaxActive(dto.getMaxActive());
    druidDataSource.setInitialSize(dto.getInitialSize());
    druidDataSource.setMaxWait(60000);
    druidDataSource.setTimeBetweenEvictionRunsMillis(300000);
    druidDataSource.setMinEvictableIdleTimeMillis(300000);
    druidDataSource.setValidationQuery("select 1");
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    druidDataSource.setPoolPreparedStatements(true);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(50);
    try {
        druidDataSource.init();
    } catch (SQLException e) {
        log.error("Can't init druidDataSource from DataSourceInfo:" + dto, e);
    }
    return druidDataSource;
}
 
Example 4
Source File: CompareWithWonderfulPool.java    From clearpool with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDruid() throws Exception {
  DruidDataSource dataSource = new DruidDataSource();
  dataSource.setInitialSize(this.corePoolSize);
  dataSource.setMaxActive(this.maxPoolSize);
  dataSource.setMinIdle(this.corePoolSize);
  dataSource.setPoolPreparedStatements(true);
  dataSource.setDriverClassName(this.driverClassName);
  dataSource.setUrl(this.url);
  dataSource.setPoolPreparedStatements(true);
  dataSource.setUsername(this.username);
  dataSource.setPassword(this.password);
  dataSource.setValidationQuery("select 1");
  dataSource.setTestOnBorrow(false);
  for (int i = 0; i < this.loop; ++i) {
    ThreadProcessUtils.process(dataSource, "druid", this.count, threadCount, physicalCon);
  }
  System.out.println();
}
 
Example 5
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
protected void checkSlave(DbNodeEntity dbNodeEntity) throws SQLException {
	// 检查slave
	if (hasSlave(dbNodeEntity)) {
		DruidDataSource dataSource = dataSourceFactory.createDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUsername(dbNodeEntity.getDbUserNameBak());
		dataSource.setPassword(dbNodeEntity.getDbPassBak());
		dataSource.setUrl(getCon(dbNodeEntity, false));
		dataSource.setInitialSize(1);
		dataSource.setMinIdle(0);
		dataSource.setMaxActive(1);
		dataSource.init();
		dataSource = null;
	}
}
 
Example 6
Source File: DruidConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Bean     //声明其为Bean实例
@Primary  //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(url);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    //configuration
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    try {
        datasource.setFilters(filters);
    } catch (SQLException e) {
        logger.error("druid configuration initialization filter: " + e);
    }
    datasource.setConnectionProperties(connectionProperties);
    logger.debug("druid configuration datasource 成功"  + datasource);
    logger.debug("druid configuration datasource 成功"  + name);
    return datasource;
}
 
Example 7
Source File: DynamicDBUtil.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获取数据源【最底层方法,不要随便调用】
 *
 * @param dbSource
 * @return
 */
private static DruidDataSource getJdbcDataSource(final DynamicDataSourceModel dbSource) {
    DruidDataSource dataSource = new DruidDataSource();

    String driverClassName = dbSource.getDbDriver();
    String url = dbSource.getDbUrl();
    String dbUser = dbSource.getDbUsername();
    String dbPassword = dbSource.getDbPassword();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    //dataSource.setValidationQuery("SELECT 1 FROM DUAL");
    dataSource.setTestWhileIdle(true);
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setBreakAfterAcquireFailure(true);
    dataSource.setConnectionErrorRetryAttempts(0);
    dataSource.setUsername(dbUser);
    dataSource.setMaxWait(60000);
    dataSource.setPassword(dbPassword);

    log.info("******************************************");
    log.info("*                                        *");
    log.info("*====【"+dbSource.getCode()+"】=====Druid连接池已启用 ====*");
    log.info("*                                        *");
    log.info("******************************************");
    return dataSource;
}
 
Example 8
Source File: DruidIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws InterruptedException, SQLException {

    DruidDataSource dataSource = new DruidDataSource();

    dataSource.setUrl(JDBC_URL);
    dataSource.setValidationQuery("select 'x'");
    dataSource.setUsername("test");
    dataSource.setPassword("test");

    dataSource.init();
    try {
        Connection connection = dataSource.getConnection();
        Assert.assertNotNull(connection);

        connection.close();

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        verifier.verifyTrace(event(serviceType, getConnectionMethod));
        verifier.verifyTrace(event(serviceType, closeConnectionMethod));
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 9
Source File: DbConfig.java    From oauth-boot with MIT License 5 votes vote down vote up
/**
* <!-- 配置初始化大小、最小、最大 -->
    <property name="initialSize" value="10" />
    <property name="minIdle" value="30" />
    <property name="maxActive" value="300" />
    <!-- 配置获取连接等待超时的时间 -->
    <property name="maxWait" value="3600000" />
    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    <property name="minEvictableIdleTimeMillis" value="30000" />
    <property name="validationQuery" value="SELECT 'x' FROM dual" />
    <property name="testWhileIdle" value="true" />
    <property name="testOnBorrow" value="false" />
    <property name="testOnReturn" value="false" />
    <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
    <property name="poolPreparedStatements" value="true" />
    <property name="maxPoolPreparedStatementPerConnectionSize"
    value="20" />
*
* */
@Bean
@Primary
public DataSource dataSource() {
    DruidDataSource dr = new DruidDataSource();
    dr.setUsername(this.username);
    dr.setPassword(this.password);
    dr.setDriverClassName(this.driverClassName);
    dr.setUrl(this.url);

    this.logger.info(this.url+":"+this.username+":"+this.password);

    dr.setInitialSize(10);
    dr.setMinIdle(30);
    dr.setMaxActive(300);
    dr.setMaxWait(3600000);
    dr.setTimeBetweenEvictionRunsMillis(60000);
    dr.setMinEvictableIdleTimeMillis(30000);
    dr.setValidationQuery("select 'X' from dual");
    dr.setTestWhileIdle(true);
    dr.setTestOnBorrow(false);
    dr.setTestOnReturn(false);
    dr.setPoolPreparedStatements(true);
    dr.setMaxPoolPreparedStatementPerConnectionSize(20);

    return dr;
}
 
Example 10
Source File: DruidDataSourceConfigurer.java    From FlyCms with MIT License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(this.dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);

    //configuration
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    try {
        datasource.setFilters(filters);
    } catch (SQLException e) {
        logger.error("druid configuration initialization filter", e);
    }
    datasource.setConnectionProperties(connectionProperties);

    return datasource;
}
 
Example 11
Source File: EasyTransTestConfiguration.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
/**
 * 创建多个数据源来模拟分布式服务环境
 * @param properties
 * @return
 */
private DruidDataSource createDatasource(EasyTransTestProperties properties) {
	DruidDataSource ds = new DruidDataSource();
	ds.setUrl(properties.getUrl());
	ds.setUsername(properties.getUsername());
	ds.setPassword(properties.getPassword());
	ds.setMaxActive(10);
	ds.setInitialSize(1);
	ds.setMinIdle(1);
	ds.setPoolPreparedStatements(true);
	return ds;
}
 
Example 12
Source File: DbConfiguration.java    From flower with Apache License 2.0 5 votes vote down vote up
@Bean("dataSource")
public DruidDataSource getDataSource() throws SQLException {
  DruidDataSource dataSource = new DruidDataSource();
  dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
  dataSource.setUrl("jdbc:mysql://localhost:3306/flower?characterEncoding=UTF-8&serverTimezone=GMT%2B8");
  dataSource.setUsername("root");
  dataSource.setPassword("flower123");
  dataSource.setInitialSize(5);
  dataSource.setMaxActive(30);
  dataSource.setValidationQuery("select version()");
  dataSource.init();
  return dataSource;
}
 
Example 13
Source File: MasterDataSourceConfig.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
@Bean(name = "masterDataSource")
@Primary //标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。 
public DataSource masterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(url);  
    dataSource.setUsername(username);  
    dataSource.setPassword(password);  
    dataSource.setDriverClassName(driverClassName);  
      
    //具体配置 
    dataSource.setInitialSize(initialSize);  
    dataSource.setMinIdle(minIdle);  
    dataSource.setMaxActive(maxActive);  
    dataSource.setMaxWait(maxWait);  
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
    dataSource.setValidationQuery(validationQuery);  
    dataSource.setTestWhileIdle(testWhileIdle);  
    dataSource.setTestOnBorrow(testOnBorrow);  
    dataSource.setTestOnReturn(testOnReturn);  
    dataSource.setPoolPreparedStatements(poolPreparedStatements);  
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);  
    try {  
        dataSource.setFilters(filters);  
    } catch (SQLException e) { 
    	e.printStackTrace();
    }  
    dataSource.setConnectionProperties(connectionProperties);  
    return dataSource;
}
 
Example 14
Source File: DruidConfig.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
public DataSource newInstanceDruidDataSource() throws Exception {
    if (mydataSource != null) {
        return mydataSource;
    }
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(this.url);
    druidDataSource.setUsername(this.username);
    druidDataSource.setPassword(this.password);
    druidDataSource.setDriverClassName(this.driverClassName);
    druidDataSource.setInitialSize(this.initialSize);
    druidDataSource.setMaxActive(this.maxActive);
    druidDataSource.setMinIdle(this.minIdle);
    druidDataSource.setMaxWait(this.maxWait);
    druidDataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
    druidDataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
    druidDataSource.setValidationQuery(this.validationQuery);
    druidDataSource.setTestWhileIdle(this.testWhileIdle);
    druidDataSource.setTestOnBorrow(this.testOnBorrow);
    druidDataSource.setTestOnReturn(this.testOnReturn);
    druidDataSource.setPoolPreparedStatements(this.poolPreparedStatements);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
    druidDataSource.setFilters(this.filters);

    try {
        if (null != druidDataSource) {
            druidDataSource.setFilters("wall,stat");
            druidDataSource.setUseGlobalDataSourceStat(true);
            druidDataSource.init();
        }
    } catch (Exception e) {
        throw new RuntimeException("load datasource error, dbProperties is :", e);
    }
    synchronized (this) {
        mydataSource = druidDataSource;
    }
    druidDataSource.init();
    return druidDataSource;
}
 
Example 15
Source File: CobarFactory.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public static CobarAdapter getCobarAdapter(String cobarNodeName) throws IOException {
    CobarAdapter cAdapter = new CobarAdapter();
    Properties prop = new Properties();
    prop.load(CobarFactory.class.getClassLoader().getResourceAsStream("cobarNode.properties"));
    DruidDataSource ds = new DruidDataSource();
    String user = prop.getProperty(cobarNodeName + ".user").trim();
    String password = prop.getProperty(cobarNodeName + ".password").trim();
    String ip = prop.getProperty(cobarNodeName + ".ip").trim();
    int managerPort = Integer.parseInt(prop.getProperty(cobarNodeName + ".manager.port").trim());
    int maxActive = -1;
    int minIdle = 0;
    long timeBetweenEvictionRunsMillis = 10 * 60 * 1000;
    // int numTestsPerEvictionRun = Integer.MAX_VALUE;
    long minEvictableIdleTimeMillis = DruidDataSource.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(new StringBuilder().append("jdbc:mysql://")
        .append(ip)
        .append(":")
        .append(managerPort)
        .append("/")
        .toString());
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // ds.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    cAdapter.setDataSource(ds);
    return cAdapter;
}
 
Example 16
Source File: JDBCTest.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DruidDataSource ds = new DruidDataSource();
    ds.setUrl("jdbc:mysql://42.120.217.1/DRDS_1053599184310491_HOIBS_CLUSTER?characterEncoding=utf8");
    ds.setUsername("DRDS_1053599184310491_HOIBS_CLUSTER");
    ds.setPassword("hfd000999");

    Connection conn = ds.getConnection();
    conn.prepareStatement("set names utf8mb4").executeUpdate();

    byte[] b3 = { (byte) 0xF0, (byte) 0x9F, (byte) 0x90, (byte) 0xA0 }; // 0xF0
                                                                        // 0x9F
                                                                        // 0x8F
                                                                        // 0x80

    String text = new String(b3, "utf-8");
    text.getBytes("utf-8");
    PreparedStatement ps = conn.prepareStatement("insert into INS_EBAY_MESSAGE(msg_id,deadline_time,folder,item_end_time,item_no,message_no,is_read,receive_time,recipient_usr_id,sender,send_to_name,subject,create_time,order_id,usr_id,text) values(?,'2015-03-24 16:37:16','0','2014-02-23 02:42:29','181330498504','54529786058','true','2014-03-24 16:37:16','spring.inc','babz.brinz','spring.inc','babz.brinzClearForAppleiPhone55G5SHotSale0.5mmUltraThinMatteBackCaseSkin','2014-06-30 18:19:26',7001,4010,?);");
    long msg_id = System.currentTimeMillis();
    ps.setLong(1, msg_id);
    ps.setString(2, text);
    ps.executeUpdate();

    ps = conn.prepareStatement("select * from INS_EBAY_MESSAGE where msg_id=?");
    ps.setLong(1, msg_id);

    ResultSet rs = ps.executeQuery();

    while (rs.next()) {
        System.out.println(rs.getString("text").getBytes());
    }
    ps.close();
    conn.close();
    System.out.println("query done");
}
 
Example 17
Source File: ConnectionTest.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
    try {
        DruidDataSource ds = new DruidDataSource();
        ds.setUsername("test");
        ds.setPassword("");
        ds.setUrl("jdbc:mysql://10.20.153.178:9066/");
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setMaxActive(-1);
        ds.setMinIdle(0);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        // ds.setNumTestsPerEvictionRun(Integer.MAX_VALUE);
        ds.setMinEvictableIdleTimeMillis(DruidDataSource.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
        Connection conn = ds.getConnection();

        Statement stm = conn.createStatement();
        stm.execute("show @@version");

        ResultSet rst = stm.getResultSet();
        rst.next();
        String version = rst.getString("VERSION");

        System.out.println(version);
        ds.close();
    } catch (Exception exception) {
        System.out.println("10.20.153.178:9066   " + exception.getMessage() + exception);
    }
}
 
Example 18
Source File: BaseGroupTest.java    From tddl with Apache License 2.0 5 votes vote down vote up
public static DataSource getMySQLDataSource(int num) {
    if (num > 2) {
        num = 2;
    }
    DruidDataSource ds = new DruidDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUsername("tddl");
    ds.setPassword("tddl");
    ds.setUrl("jdbc:mysql://10.232.31.154/tddl_sample_" + num);
    return ds;

}
 
Example 19
Source File: DBTest.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
@Test
public void test01() throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    // dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
    // dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:49161:XE");
    // dataSource.setUsername("mytest");
    // dataSource.setPassword("m121212");

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true");
    dataSource.setUsername("root");
    dataSource.setPassword("121212");

    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(2);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);

    dataSource.init();

    Connection conn = dataSource.getConnection();

    conn.setAutoCommit(false);
    PreparedStatement pstmt = conn
        .prepareStatement("insert into user (id,name,role_id,c_time,test1,test2) values (?,?,?,?,?,?)");

    java.util.Date now = new java.util.Date();
    for (int i = 1; i <= 10000; i++) {
        pstmt.clearParameters();
        pstmt.setLong(1, (long) i);
        pstmt.setString(2, "test_" + i);
        pstmt.setLong(3, (long) i % 4 + 1);
        pstmt.setDate(4, new java.sql.Date(now.getTime()));
        pstmt.setString(5, null);
        pstmt.setBytes(6, null);

        pstmt.execute();
        if (i % 5000 == 0) {
            conn.commit();
        }
    }
    conn.commit();

    pstmt.close();

    // Statement stmt = conn.createStatement();
    // ResultSet rs = stmt.executeQuery("select * from user t where 1=2");
    //
    // ResultSetMetaData rsm = rs.getMetaData();
    // int cnt = rsm.getColumnCount();
    // for (int i = 1; i <= cnt; i++) {
    // System.out.println(rsm.getColumnName(i) + " " + rsm.getColumnType(i));
    // }

    // rs.close();
    // stmt.close();

    // PreparedStatement pstmt = conn
    // .prepareStatement("insert into tb_user (id,name,role_id,c_time,test1,test2)
    // values (?,?,?,?,?,?)");
    // pstmt.setBigDecimal(1, new BigDecimal("5"));
    // pstmt.setString(2, "test");
    // pstmt.setBigDecimal(3, new BigDecimal("1"));
    // pstmt.setDate(4, new Date(new java.util.Date().getTime()));
    // byte[] a = { (byte) 1, (byte) 2 };
    // pstmt.setBytes(5, a);
    // pstmt.setBytes(6, a);
    // pstmt.execute();
    //
    // pstmt.close();

    conn.close();
    dataSource.close();
}
 
Example 20
Source File: DataSourceFactory.java    From yugong with GNU General Public License v2.0 4 votes vote down vote up
private DataSource createDataSource(String url, String userName, String password, DbType dbType, Properties props) {
    try {
        int maxActive = Integer.valueOf(props.getProperty("maxActive", String.valueOf(this.maxActive)));
        if (maxActive < 0) {
            maxActive = 200;
        }
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        dataSource.setUseUnfairLock(true);
        dataSource.setNotFullTimeoutRetryCount(2);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxWait(maxWait);
        dataSource.setDriverClassName(dbType.getDriver());
        // 动态的参数
        if (props != null && props.size() > 0) {
            for (Map.Entry<Object, Object> entry : props.entrySet()) {
                dataSource.addConnectionProperty(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
            }
        }

        if (dbType.isOracle()) {
            dataSource.addConnectionProperty("restrictGetTables", "true");
            dataSource.addConnectionProperty("oracle.jdbc.V8Compatible", "true");
            dataSource.setValidationQuery("select 1 from dual");
            dataSource.setExceptionSorter("com.alibaba.druid.pool.vendor.OracleExceptionSorter");
        } else if (dbType.isMysql() || dbType.isDRDS()) {
            dataSource.addConnectionProperty("useServerPrepStmts", "false");
            dataSource.addConnectionProperty("rewriteBatchedStatements", "true");
            dataSource.addConnectionProperty("allowMultiQueries", "true");
            dataSource.addConnectionProperty("readOnlyPropagatesToServer", "false");
            dataSource.setValidationQuery("select 1");
            dataSource.setExceptionSorter("com.alibaba.druid.pool.vendor.MySqlExceptionSorter");
            dataSource.setValidConnectionCheckerClassName("com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker");
        } else {
            logger.error("Unknow database type");
        }
        return dataSource;
    } catch (Throwable e) {
        throw new YuGongException("create dataSource error!", e);
    }
}