org.apache.commons.dbcp2.BasicDataSource Java Examples
The following examples show how to use
org.apache.commons.dbcp2.BasicDataSource.
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: AbstractMysqlHandler.java From adt with Apache License 2.0 | 6 votes |
public AbstractMysqlHandler() throws Exception{ shardCount = Integer.parseInt(System.getProperty(PROP_SHARD_CNT)); for(int i=0; i<shardCount; i++){ final BasicDataSource ds = new BasicDataSource(); ds.setMaxTotal(1024); ds.setMaxIdle(1024); ds.setMinIdle(0); ds.setUrl(System.getProperty(String.format(PROP_SHARD_URL, i))); ds.setUsername(System.getProperty(String.format(PROP_SHARD_USERNAME, i))); ds.setPassword(System.getProperty(String.format(PROP_SHARD_PASSWORD, i))); dataSourceList.add(ds); } // final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); // scriptEngine = scriptEngineManager.getEngineByName(SCRIPT_ENGINE_NAME); // scriptEngine.eval(System.getProperty(PROP_SCRIPT)); }
Example #2
Source File: MySQLRunner.java From replicator with Apache License 2.0 | 6 votes |
private BasicDataSource initDatasource(ServicesControl mysql, MySQLConfiguration configuration, Object driverClass, boolean runAsRoot) { String hostname = mysql.getHost(); Object port = mysql.getPort(); String schema = configuration.getSchema(); String username = runAsRoot ? "root" : configuration.getUsername(); String password = configuration.getPassword(); Objects.requireNonNull(hostname, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_HOSTNAME)); Objects.requireNonNull(schema, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_SCHEMA)); Objects.requireNonNull(username, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_USERNAME)); Objects.requireNonNull(password, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_PASSWORD)); return this.getDataSource(driverClass.toString(), hostname, Integer.parseInt(port.toString()), schema, username, password); }
Example #3
Source File: OrchestrationSpringBootEncryptTest.java From shardingsphere with Apache License 2.0 | 6 votes |
@Test @SneakyThrows(ReflectiveOperationException.class) public void assertWithEncryptDataSource() { assertTrue(dataSource instanceof OrchestrationShardingSphereDataSource); Field field = OrchestrationShardingSphereDataSource.class.getDeclaredField("dataSource"); field.setAccessible(true); ShardingSphereDataSource shardingSphereDataSource = (ShardingSphereDataSource) field.get(dataSource); BasicDataSource embedDataSource = (BasicDataSource) shardingSphereDataSource.getDataSourceMap().values().iterator().next(); assertThat(embedDataSource.getMaxTotal(), is(100)); assertThat(embedDataSource.getUsername(), is("sa")); AlgorithmProvidedEncryptRuleConfiguration configuration = (AlgorithmProvidedEncryptRuleConfiguration) shardingSphereDataSource.getSchemaContexts().getDefaultSchemaContext().getSchema().getConfigurations().iterator().next(); assertThat(configuration.getEncryptors().size(), is(1)); EncryptAlgorithm encryptAlgorithm = configuration.getEncryptors().get("order_encrypt"); assertThat(encryptAlgorithm.getType(), is("AES")); assertThat(configuration.getTables().size(), is(1)); assertThat(configuration.getTables().iterator().next().getColumns().iterator().next().getCipherColumn(), is("cipher_order_id")); }
Example #4
Source File: MultiJdbcSchemaJoinTest.java From Quicksql with MIT License | 6 votes |
/** Tests {@link com.qihoo.qsql.org.apache.calcite.adapter.jdbc.JdbcCatalogSchema}. */ @Test public void test3() throws SQLException { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(TempDb.INSTANCE.getUrl()); dataSource.setUsername(""); dataSource.setPassword(""); final JdbcCatalogSchema schema = JdbcCatalogSchema.create(null, "", dataSource, "PUBLIC"); assertThat(schema.getSubSchemaNames(), is(Sets.newHashSet("INFORMATION_SCHEMA", "PUBLIC", "SYSTEM_LOBS"))); final CalciteSchema rootSchema0 = CalciteSchema.createRootSchema(false, false, "", schema); final Driver driver = new Driver(); final CalciteJdbc41Factory factory = new CalciteJdbc41Factory(); final String sql = "select count(*) as c from information_schema.schemata"; try (Connection connection = factory.newConnection(driver, factory, "jdbc:calcite:", new Properties(), rootSchema0, null); Statement stmt3 = connection.createStatement(); ResultSet rs = stmt3.executeQuery(sql)) { assertThat(CalciteAssert.toString(rs), equalTo("C=3\n")); } }
Example #5
Source File: SinkToMySQL.java From flink-learning with Apache License 2.0 | 6 votes |
private static Connection getConnection(BasicDataSource dataSource) { dataSource.setDriverClassName("com.mysql.jdbc.Driver"); //注意,替换成自己本地的 mysql 数据库地址和用户名、密码 dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("root123456"); //设置连接池的一些参数 dataSource.setInitialSize(10); dataSource.setMaxTotal(50); dataSource.setMinIdle(2); Connection con = null; try { con = dataSource.getConnection(); log.info("创建连接池:{}", con); } catch (Exception e) { log.error("-----------mysql get connection has exception , msg = {}", e.getMessage()); } return con; }
Example #6
Source File: SqlDbConfiguration.java From jpa-unit with Apache License 2.0 | 6 votes |
public DataSource createDataSource() { final String driverClass = (String) dbConfig.get("javax.persistence.jdbc.driver"); final String connectionUrl = (String) dbConfig.get("javax.persistence.jdbc.url"); final String username = (String) dbConfig.get("javax.persistence.jdbc.user"); final String password = (String) dbConfig.get("javax.persistence.jdbc.password"); final BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(driverClass); ds.setUsername(username); ds.setPassword(password); ds.setUrl(connectionUrl); ds.setMinIdle(1); ds.setMaxIdle(2); return ds; }
Example #7
Source File: PooledXADataSourceWrapper.java From narayana-spring-boot with Apache License 2.0 | 6 votes |
/** * Wrap the provided data source and initialize the connection pool if its initial size is higher than 0. * * @param xaDataSource data source that needs to be wrapped * @return wrapped data source * @throws Exception if data source copy or connection pool initialization has failed. */ @Override protected DataSource wrapDataSourceInternal(XADataSource xaDataSource) throws Exception { BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource(); // Managed data source does't have a factory. Therefore we need to create an unmanaged data source and then copy // it's configuration to the managed one. BasicDataSource basicDataSource = getBasicDataSource(); copyFields(basicDataSource, basicManagedDataSource); basicManagedDataSource.setTransactionManager(this.transactionManager); basicManagedDataSource.setXaDataSourceInstance(xaDataSource); // Initialize the connections pool int initialSize = Integer.valueOf(this.properties.getDbcp().getOrDefault("initialSize", "0")); if (initialSize > 0) { basicManagedDataSource.setInitialSize(initialSize); basicManagedDataSource.getLogWriter(); // A trick to trigger pool initialization } return basicManagedDataSource; }
Example #8
Source File: MyDataSourceFactory.java From spring-boot with Apache License 2.0 | 6 votes |
/** * apache commons dbcp2 数据源 * * @return */ protected static DataSource getDBCP2DataSource() { //创建BasicDataSource类对象 BasicDataSource datasource = new BasicDataSource(); //数据库连接信息(必须) datasource.setDriverClassName("com.mysql.jdbc.Driver"); datasource.setUrl("jdbc:mysql://localhost:3306/ztree?useUnicode=true&characterEncoding=utf-8&useSSL=false"); datasource.setUsername("root"); datasource.setPassword("123456"); //连接池中的连接数量配置(可选) datasource.setInitialSize(10);//初始化的连接数 datasource.setMaxOpenPreparedStatements(8);//最大连接数 datasource.setMaxIdle(5);//最大空闲连接 datasource.setMinIdle(1);//最小空闲连接 return datasource; }
Example #9
Source File: DaoEnvTestSpringModuleConfig.java From herd with Apache License 2.0 | 6 votes |
/** * Get a new herd data source based on an in-memory HSQLDB database. This data source is used for loading the configuration table as an environment property * source as well as for the JPA entity manager. It will therefore create/re-create the configuration table which is required for the former. It also * inserts required values for both scenarios. * * @return the test herd data source. */ @Bean public static DataSource herdDataSource() { // Create and return a data source that can connect directly to a JDBC URL. BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(org.h2.Driver.class.getName()); basicDataSource.setUsername(""); basicDataSource.setPassword(""); basicDataSource.setUrl("jdbc:h2:mem:herdTestDb"); // Create and populate the configuration table. // This is needed for all data source method calls since it is used to create the environment property source which happens before // JPA and other non-static beans are initialized. ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(); resourceDatabasePopulator.addScript(new ClassPathResource("createConfigurationTableAndData.sql")); DatabasePopulatorUtils.execute(resourceDatabasePopulator, basicDataSource); // This is what the DataSourceInitializer does. return basicDataSource; }
Example #10
Source File: MultiJdbcSchemaJoinTest.java From calcite with Apache License 2.0 | 6 votes |
/** Tests {@link org.apache.calcite.adapter.jdbc.JdbcCatalogSchema}. */ @Test void test3() throws SQLException { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(TempDb.INSTANCE.getUrl()); dataSource.setUsername(""); dataSource.setPassword(""); final JdbcCatalogSchema schema = JdbcCatalogSchema.create(null, "", dataSource, "PUBLIC"); assertThat(schema.getSubSchemaNames(), is(Sets.newHashSet("INFORMATION_SCHEMA", "PUBLIC", "SYSTEM_LOBS"))); final CalciteSchema rootSchema0 = CalciteSchema.createRootSchema(false, false, "", schema); final Driver driver = new Driver(); final CalciteJdbc41Factory factory = new CalciteJdbc41Factory(); final String sql = "select count(*) as c from information_schema.schemata"; try (Connection connection = factory.newConnection(driver, factory, "jdbc:calcite:", new Properties(), rootSchema0, null); Statement stmt3 = connection.createStatement(); ResultSet rs = stmt3.executeQuery(sql)) { assertThat(CalciteAssert.toString(rs), equalTo("C=3\n")); } }
Example #11
Source File: ConnectionManager.java From gocd with Apache License 2.0 | 6 votes |
private BasicDataSource createDataSource() { final DbProperties dbProperties = getDbProperties(); BasicDataSource basicDataSource = new BasicDataSource(); if (isBlank(dbProperties.url())) { return DefaultH2DataSource.defaultH2DataSource(basicDataSource, dbProperties); } basicDataSource.setDriverClassName(dbProperties.driver()); basicDataSource.setUrl(dbProperties.url()); basicDataSource.setUsername(dbProperties.user()); basicDataSource.setPassword(dbProperties.password()); basicDataSource.setMaxTotal(dbProperties.maxTotal()); basicDataSource.setMaxIdle(dbProperties.maxIdle()); basicDataSource.setConnectionProperties(dbProperties.connectionPropertiesAsString()); return basicDataSource; }
Example #12
Source File: ConnectionUtils.java From FROST-Server with GNU Lesser General Public License v3.0 | 6 votes |
private static ConnectionSource setupBasicDataSource(Settings settings) { LOGGER.info("Setting up BasicDataSource for database connections."); String driver = settings.get(TAG_DB_DRIVER, ConnectionUtils.class); if (driver.isEmpty()) { throw new IllegalArgumentException("Property '" + TAG_DB_DRIVER + "' must be non-empty"); } try { Class.forName(driver); BasicDataSource ds = new BasicDataSource(); ds.setUrl(settings.get(TAG_DB_URL, ConnectionUtils.class)); ds.setUsername(settings.get(TAG_DB_USERNAME, ConnectionUtils.class)); ds.setPassword(settings.get(TAG_DB_PASSWRD, ConnectionUtils.class)); ds.setMaxIdle(settings.getInt(TAG_DB_MAXIDLE, ds.getMaxIdle())); ds.setMaxTotal(settings.getInt(TAG_DB_MAXCONN, ds.getMaxTotal())); ds.setMinIdle(settings.getInt(TAG_DB_MINIDLE, ds.getMinIdle())); return new ConnectionSourceBasicDataSource(ds); } catch (ClassNotFoundException exc) { throw new IllegalArgumentException(exc); } }
Example #13
Source File: DBCPDataSourceFactory.java From sumk with Apache License 2.0 | 6 votes |
@Override public Map<String, Integer> status(DataSource datasource) { BasicDataSource ds = null; try { ds = datasource.unwrap(BasicDataSource.class); } catch (Exception e) { Logs.db().error(e.getLocalizedMessage(), e); } if (ds == null) { Logs.db().info("ds.class({}) is not instance form BasicDataSource", datasource.getClass().getName()); return Collections.emptyMap(); } Map<String, Integer> map = new HashMap<>(); map.put("active", ds.getNumActive()); map.put("idle", ds.getNumIdle()); map.put("minIdle", ds.getMinIdle()); map.put("maxIdle", ds.getMaxIdle()); map.put("maxTotal", ds.getMaxTotal()); return map; }
Example #14
Source File: H2BackupProcessorTest.java From gocd with Apache License 2.0 | 6 votes |
@Test void shouldTakeBackup(@TempDir Path tempDir) throws SQLException { File originalDir = tempDir.resolve("originalDb").toFile(); originalDir.mkdirs(); File backupDir = tempDir.resolve("backupDir").toFile(); backupDir.mkdirs(); assertThat(backupDir.listFiles()).isNullOrEmpty(); try (BasicDataSource ds = new BasicDataSource()) { ds.setDriverClassName(org.h2.Driver.class.getName()); ds.setUrl("jdbc:h2:" + new File(originalDir, "test").getAbsoluteFile()); ds.setUsername("sa"); ds.setPassword(""); new H2BackupProcessor().backup(backupDir, ds, null); } assertThat(backupDir.listFiles()).containsExactly(new File(backupDir, "db.zip")); }
Example #15
Source File: ResourceFactory.java From o2oa with GNU Affero General Public License v3.0 | 6 votes |
private static void external_dbcp2() throws Exception { for (ExternalDataSource ds : Config.externalDataSources()) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(ds.getDriverClassName()); dataSource.setUrl(ds.getUrl()); dataSource.setInitialSize(0); dataSource.setMinIdle(0); dataSource.setMaxTotal(ds.getMaxTotal()); dataSource.setMaxIdle(ds.getMaxTotal()); dataSource.setTestOnCreate(false); dataSource.setTestWhileIdle(false); dataSource.setTestOnReturn(false); dataSource.setTestOnBorrow(false); dataSource.setUsername(ds.getUsername()); dataSource.setPassword(ds.getPassword()); String name = Config.externalDataSources().name(ds); new Resource(Config.RESOURCE_JDBC_PREFIX + name, dataSource); } }
Example #16
Source File: DataSourceManager.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private static void createPoolIfAbsent(IDataSource dataSource) { Assert.assertNotNull(dataSource, "Missing input datasource"); Assert.assertNotNull(dataSource.getJdbcPoolConfiguration(), "Connection pool information is not provided"); logger.debug("Creating connection pool for datasource " + dataSource.getLabel()); BasicDataSource pool = new BasicDataSource(); pool.setDriverClassName(dataSource.getDriver()); pool.setUrl(dataSource.getUrlConnection()); pool.setUsername(dataSource.getUser()); pool.setPassword(dataSource.getPwd()); pool.setMaxTotal(dataSource.getJdbcPoolConfiguration().getMaxTotal()); pool.setMaxWaitMillis(dataSource.getJdbcPoolConfiguration().getMaxWait()); pool.setRemoveAbandonedOnBorrow(dataSource.getJdbcPoolConfiguration().getRemoveAbandonedOnBorrow()); pool.setRemoveAbandonedOnMaintenance(dataSource.getJdbcPoolConfiguration().getRemoveAbandonedOnMaintenance()); pool.setRemoveAbandonedTimeout(dataSource.getJdbcPoolConfiguration().getAbandonedTimeout()); pool.setLogAbandoned(dataSource.getJdbcPoolConfiguration().getLogAbandoned()); pool.setTestOnReturn(dataSource.getJdbcPoolConfiguration().getTestOnReturn()); pool.setTestWhileIdle(dataSource.getJdbcPoolConfiguration().getTestWhileIdle()); pool.setTimeBetweenEvictionRunsMillis(dataSource.getJdbcPoolConfiguration().getTimeBetweenEvictionRuns()); pool.setMinEvictableIdleTimeMillis(dataSource.getJdbcPoolConfiguration().getMinEvictableIdleTimeMillis()); pool.setValidationQuery(dataSource.getJdbcPoolConfiguration().getValidationQuery()); dataSources.put(dataSource, pool); }
Example #17
Source File: SpringTest.java From java-jdbc with Apache License 2.0 | 6 votes |
@Test public void spring_with_ignored_statement() throws Exception { BasicDataSource dataSource = getDataSource(false, Arrays.asList( "CREATE TABLE ignored (id INTEGER, TEST VARCHAR)", "INSERT INTO ignored (id, \\\"TEST\\\") VALUES (1, 'value')" )); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("CREATE TABLE ignored (id INTEGER, TEST VARCHAR)"); jdbcTemplate.execute("INSERT INTO ignored (id, \"TEST\") VALUES (1, 'value')"); jdbcTemplate.execute("CREATE TABLE not_ignored (id INTEGER)"); dataSource.close(); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertEquals(DB_CONNECTION_SPAN_COUNT + 1, finishedSpans.size()); checkNoEmptyTags(finishedSpans); }
Example #18
Source File: SpringTest.java From java-jdbc with Apache License 2.0 | 6 votes |
@Test public void spring_with_parent_and_active_span_only() throws Exception { final MockSpan parent = mockTracer.buildSpan("parent").start(); try (Scope ignored = mockTracer.activateSpan(parent)) { BasicDataSource dataSource = getDataSource(true); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("CREATE TABLE with_parent_skip_1 (id INTEGER)"); jdbcTemplate.execute("CREATE TABLE with_parent_skip_2 (id INTEGER)"); dataSource.close(); } parent.finish(); List<MockSpan> spans = mockTracer.finishedSpans(); assertEquals(DB_CONNECTION_SPAN_COUNT + 3, spans.size()); checkSameTrace(spans); checkNoEmptyTags(spans); }
Example #19
Source File: SpringTest.java From java-jdbc with Apache License 2.0 | 6 votes |
@Test public void spring_with_parent() throws Exception { final MockSpan parent = mockTracer.buildSpan("parent").start(); try (Scope ignored = mockTracer.activateSpan(parent)) { BasicDataSource dataSource = getDataSource(false); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("CREATE TABLE with_parent_1 (id INTEGER)"); jdbcTemplate.execute("CREATE TABLE with_parent_2 (id INTEGER)"); dataSource.close(); } parent.finish(); List<MockSpan> spans = mockTracer.finishedSpans(); assertEquals(DB_CONNECTION_SPAN_COUNT + 3, spans.size()); checkSameTrace(spans); checkNoEmptyTags(spans); }
Example #20
Source File: DefaultH2DataSource.java From gocd with Apache License 2.0 | 6 votes |
public static BasicDataSource defaultH2DataSource(BasicDataSource basicDataSource, DbProperties properties) { File defaultDbDir = new File("db/h2db"); if (!defaultDbDir.exists()) { defaultDbDir.mkdirs(); } String defaultCacheSizeInMB = String.valueOf(128 * 1024); //128MB String defaultH2Url = "jdbc:h2:./db/h2db/cruise" + ";DB_CLOSE_DELAY=-1" + ";DB_CLOSE_ON_EXIT=FALSE" + // do not close the DB on JVM exit // ";MVCC=TRUE" + ";CACHE_SIZE=" + defaultCacheSizeInMB + ";TRACE_MAX_FILE_SIZE=16" + // http://www.h2database.com/html/features.html#trace_options ";TRACE_LEVEL_FILE=1" // http://www.h2database.com/html/features.html#trace_options ; basicDataSource.setUrl(defaultH2Url); basicDataSource.setUsername(StringUtils.defaultIfBlank(properties.user(), "sa")); basicDataSource.setPassword(StringUtils.stripToEmpty(properties.password())); return basicDataSource; }
Example #21
Source File: TestEntandoJndiUtils.java From entando-core with GNU Lesser General Public License v3.0 | 6 votes |
private static void createDatasource(String dsNameControlKey, SimpleNamingContextBuilder builder, Properties testConfig) { String beanName = testConfig.getProperty("jdbc." + dsNameControlKey + ".beanName"); try { String className = testConfig.getProperty("jdbc." + dsNameControlKey + ".driverClassName"); String url = testConfig.getProperty("jdbc." + dsNameControlKey + ".url"); String username = testConfig.getProperty("jdbc." + dsNameControlKey + ".username"); String password = testConfig.getProperty("jdbc." + dsNameControlKey + ".password"); Class.forName(className); BasicDataSource ds = new BasicDataSource(); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); ds.setMaxTotal(12); ds.setMaxIdle(4); ds.setDriverClassName(className); builder.bind("java:comp/env/jdbc/" + beanName, ds); } catch (Throwable t) { throw new RuntimeException("Error on creation datasource '" + beanName + "'", t); } logger.debug("created datasource {}", beanName); }
Example #22
Source File: DBCPDataSourceServiceImporter.java From attic-polygene-java with Apache License 2.0 | 5 votes |
@Override protected BasicDataSource setupDataSourcePool( DataSourceConfiguration config ) throws Exception { BasicDataSource pool = new BasicDataSource(); Class.forName( config.driver().get() ); pool.setDriverClassName( config.driver().get() ); pool.setUrl( config.url().get() ); if ( !config.username().get().equals( "" ) ) { pool.setUsername( config.username().get() ); pool.setPassword( config.password().get() ); } if ( config.minPoolSize().get() != null ) { pool.setMinIdle( config.minPoolSize().get() ); } if ( config.maxPoolSize().get() != null ) { pool.setMaxTotal( config.maxPoolSize().get() ); } if ( config.loginTimeoutSeconds().get() != null ) { pool.setLoginTimeout( config.loginTimeoutSeconds().get() ); } if ( config.maxConnectionAgeSeconds().get() != null ) { pool.setMinEvictableIdleTimeMillis( config.maxConnectionAgeSeconds().get() * 1000 ); } if ( config.validationQuery().get() != null ) { pool.setValidationQuery( config.validationQuery().get() ); } return pool; }
Example #23
Source File: ResourcesJsonTest.java From tomee with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { assertNotNull(bean.datasource()); assertTrue(bean.datasource() instanceof BasicDataSource); final BasicDataSource ds = (BasicDataSource) bean.datasource(); assertEquals("org.hsqldb.jdbcDriver", ds.getDriverClassName()); assertEquals("not:used:url", ds.getUrl()); assertEquals("foo", ds.getUsername()); assertEquals("bar", ds.getPassword()); assertNotNull(bean.resource()); assertEquals("ok", bean.resource().attr); }
Example #24
Source File: DataSourceUtilTest.java From shardingsphere with Apache License 2.0 | 5 votes |
@Test public void assertDataSourceForDBCPAndHyphen() throws ReflectiveOperationException { BasicDataSource actual = (BasicDataSource) DataSourceUtil.getDataSource(BasicDataSource.class.getName(), getDataSourcePoolProperties("driver-class-name", "url", "username")); assertThat(actual.getDriverClassName(), is(org.h2.Driver.class.getName())); assertThat(actual.getUrl(), is("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL")); assertThat(actual.getUsername(), is("sa")); }
Example #25
Source File: AppConfig.java From Spring-Framework-Essentials with MIT License | 5 votes |
@Bean(name = "dataSource") @Profile("prod") public DataSource dataSourceForProd() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("db.driver")); dataSource.setUrl(env.getProperty("db.url")); dataSource.setUsername(env.getProperty("db.user")); dataSource.setPassword(env.getProperty("db.pass")); return dataSource; }
Example #26
Source File: ConfigCenterTest.java From shardingsphere with Apache License 2.0 | 5 votes |
private DataSource createDataSourceWithConnectionInitSqls(final String name) { BasicDataSource result = new BasicDataSource(); result.setDriverClassName("com.mysql.jdbc.Driver"); result.setUrl("jdbc:mysql://localhost:3306/" + name); result.setUsername("root"); result.setPassword("root"); result.setConnectionInitSqls(Arrays.asList("set names utf8mb4;", "set names utf8;")); return result; }
Example #27
Source File: OrchestrationShardingSphereDataSourceTest.java From shardingsphere with Apache License 2.0 | 5 votes |
private Map<String, DataSourceConfiguration> getDataSourceConfigurations() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"); dataSource.setUsername("sa"); dataSource.setPassword(""); Map<String, DataSourceConfiguration> result = new LinkedHashMap<>(); result.put("ds_m", DataSourceConfiguration.getDataSourceConfiguration(dataSource)); result.put("ds_s", DataSourceConfiguration.getDataSourceConfiguration(dataSource)); result.put("ds_0", DataSourceConfiguration.getDataSourceConfiguration(dataSource)); return result; }
Example #28
Source File: ResultSetController.java From ZenQuery with Apache License 2.0 | 5 votes |
private List<Map<String, Object>> getResultRows(Integer id, String variables) { Query query = queryDAO.find(id); DatabaseConnection databaseConnection = databaseConnectionDAO.find(query.getDatabaseConnectionId()); List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>(); try { BasicDataSource dataSource = dataSourceFactory.getBasicDataSource( databaseConnection.getUrl(), databaseConnection.getUsername(), databaseConnection.getPassword() ); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); if (variables != null) { List<Object> arguments = new ArrayList<Object>(); String[] extractedVariables = variables.split(","); for (String variable : extractedVariables) { try { arguments.add(Long.parseLong(variable)); } catch(NumberFormatException noLong) { try { arguments.add(Double.parseDouble(variable)); } catch(NumberFormatException noDouble) { arguments.add(variable); } } } rows = jdbcTemplate.queryForList(query.getContent(), arguments.toArray()); } else { rows = jdbcTemplate.queryForList(query.getContent()); } } catch (Exception e) { logger.debug(e); } return rows; }
Example #29
Source File: DbUnitDatabaseConnectionDecorator.java From jpa-unit with Apache License 2.0 | 5 votes |
@Override public void beforeAll(final TestInvocation invocation) throws Exception { final ExecutionContext context = invocation.getContext(); final BasicDataSource ds = (BasicDataSource) context.getData(Constants.KEY_DATA_SOURCE); final IDatabaseConnection connection = DatabaseConnectionFactory.openConnection(ds); connection.getConfig().setPropertiesByString( DbUnitConfigurationLoader.loadConfiguration(ResourceLocator.getResource("dbunit.properties"))); context.storeData(Constants.KEY_CONNECTION, connection); }
Example #30
Source File: DbTests.java From morpheus-core with Apache License 2.0 | 5 votes |
/** * Returns a newly created DataSource based on Apache Commons DBCP * @param dbType the database type * @param path the path to the database file * @return the newly created data source */ private static DataSource createDataSource(DbType dbType, File path) { System.out.println("Creating DataSource for " + path.getAbsolutePath()); path.getParentFile().mkdirs(); final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDefaultAutoCommit(true); switch (dbType) { case H2: dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2://" + path.getAbsolutePath()); dataSource.setUsername("sa"); return dataSource; case HSQL: dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:" + path.getAbsolutePath()); dataSource.setUsername("sa"); return dataSource; case SQLITE: dataSource.setDriverClassName("org.sqlite.JDBC"); dataSource.setUrl("jdbc:sqlite:" + path.getAbsolutePath()); dataSource.setUsername(""); dataSource.setPassword(""); return dataSource; } return dataSource; }