org.springframework.jdbc.datasource.DriverManagerDataSource Java Examples

The following examples show how to use org.springframework.jdbc.datasource.DriverManagerDataSource. 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: MyUtils.java    From Jantent with MIT License 6 votes vote down vote up
public static DataSource getNewDataSource() {
    lock.lock();
    try {
        if (dataSource == null) {
            Properties properties = MyUtils.getPropFromFile("classpath:application-jdbc.properties");
            if (properties.size() == 0) {
                return dataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            dataSource = managerDataSource;
        }

    } finally {
        lock.unlock();
    }
    return dataSource;
}
 
Example #2
Source File: MyDataSource.java    From luckwheel with Apache License 2.0 6 votes vote down vote up
@Bean
public JdbcTemplate mydataSource(){
    // JDBC模板依赖于连接池来获得数据的连接,所以必须先要构造连接池
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(url);
    dataSource.setUsername(name);
    dataSource.setPassword(pass);

    // 创建JDBC模板
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    // 这里也可以使用构造方法
    jdbcTemplate.setDataSource(dataSource);

    return jdbcTemplate;
}
 
Example #3
Source File: MysqlAccountManagementService.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Override
public ResourceItem createItem(ResourceItem item) {
    Map<String, String> additionalProperties = item.getAdditionalPropertiesMap();
    String username = additionalProperties.get("username");
    String password = additionalProperties.get("password");
    if (username == null || password == null) {
        throw new WecubeCoreException("Username or password is missing");
    }

    DriverManagerDataSource dataSource = newDatasource(item);
    try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();) {
        log.info("password before decrypt={}", password);
        String rawPassword = EncryptionUtils.decryptWithAes(password,
                resourceProperties.getPasswordEncryptionSeed(), item.getName());
        statement.executeUpdate(String.format("CREATE USER `%s` IDENTIFIED BY '%s'", username, rawPassword));
        statement.executeUpdate(String.format("GRANT ALL ON %s.* TO %s@'%%' IDENTIFIED BY '%s'", item.getName(),
                username, rawPassword));
    } catch (Exception e) {
        String errorMessage = String.format("Failed to create account [username = %s]", username);
        log.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
    return item;
}
 
Example #4
Source File: DatabaseStepsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testWaitTwiceUntilQueryReturnedDataEqualToTable() throws Exception
{
    mockRowsFilterAsNOOP();

    ResultSet rsFirst = mockResultSet(COL1, VAL1);
    ResultSet rsSecond = mockResultSet(COL1, VAL2);
    Statement stmt = mock(Statement.class);
    when(stmt.executeQuery(QUERY)).thenReturn(rsFirst).thenReturn(rsSecond);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    lenient().when(dataSources.get(DB_KEY)).thenReturn(dataSource);

    when(softAssert.assertTrue(QUERY_RESULTS_ARE_EQUAL, true)).thenReturn(true);
    databaseSteps.waitForDataAppearance(TWO_SECONDS, 10, QUERY, DB_KEY, new ExamplesTable(EXAMPLES_TABLE));
    verify(attachmentPublisher).publishAttachment(eq(QUERIES_STATISTICS_FTL),
            any(Map.class), eq(QUERIES_STATISTICS));
    verify(softAssert).assertTrue(QUERY_RESULTS_ARE_EQUAL, true);
}
 
Example #5
Source File: DatabaseStepsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldThrowIllegalStateExceptionInCaseOfDataIntegrityViolationException() throws SQLException
{
    DataIntegrityViolationException cause =
            new DataIntegrityViolationException("A result was returned when none was expected.");
    Statement stmt = mock(Statement.class);
    when(stmt.executeUpdate(QUERY)).thenThrow(cause);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    when(dataSources.get(DB_KEY)).thenReturn(dataSource);
    IllegalStateException actual = assertThrows(IllegalStateException.class,
        () -> databaseSteps.executeSql(QUERY, DB_KEY));
    assertEquals(cause, actual.getCause());
    assertEquals(actual.getMessage(), "Exception occured during query execution.\n"
            + "If you are trying execute SELECT query consider using step:"
            + "When I execute SQL query '$sqlQuery' and save the result to the $scopes variable '$variableName'");
}
 
Example #6
Source File: coreJDBC.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	//Postgres database we are using
       dataSource.setDriverClassName("org.postgresql.Driver");
       dataSource.setUrl("jdbc:postgresql://localhost:5432/TestDB");
       dataSource.setUsername("test");
       dataSource.setPassword("test");        
       
	String query = "SELECT COUNT(*) FROM ACCOUNT";	    
    try (Connection conn = dataSource.getConnection();
    		Statement statement =  conn.createStatement(); 
    		ResultSet rsltSet = statement.executeQuery(query)) 
    {
      if(rsltSet.next()){ 
      int count = rsltSet.getInt(1);
      System.out.println("count : " + count);
      }
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }   
    
}
 
Example #7
Source File: TaleUtils.java    From my-site with Apache License 2.0 6 votes vote down vote up
/**
 * 获取新的数据源
 *
 * @return
 */
public static DataSource getNewDataSource() {
    if (newDataSource == null) synchronized (TaleUtils.class) {
        if (newDataSource == null) {
            Properties properties = TaleUtils.getPropFromFile("application-default.properties");
            if (properties.size() == 0) {
                return newDataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            newDataSource = managerDataSource;
        }
    }
    return newDataSource;
}
 
Example #8
Source File: ProdDataConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Lazy
@Bean(name = {"one", "two", "dataSource"})
public DataSource dataSource() {
	DriverManagerDataSource ds = new DriverManagerDataSource();
	ds.setDriverClassName(driverClassName);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
	return ds;
}
 
Example #9
Source File: RepositoryConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DriverManagerDataSource getDataSource() {
	final DriverManagerDataSource  ds = new DriverManagerDataSource();
	ds.setDriverClassName(driverClassName);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
	return ds;
}
 
Example #10
Source File: MysqlDatabaseManagementService.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
private DriverManagerDataSource newDatasource(ResourceItem item) {
    String password = EncryptionUtils.decryptWithAes(item.getResourceServer().getLoginPassword(), resourceProperties.getPasswordEncryptionSeed(), item.getResourceServer().getName());
    DriverManagerDataSource dataSource = newMysqlDatasource(
            item.getResourceServer().getHost(),
            item.getResourceServer().getPort(),
            item.getResourceServer().getLoginUsername(),
            password);
    log.info(String.format("Created new data source [host:%s,port:%s,username:%s]",item.getResourceServer().getHost(),item.getResourceServer().getPort(),
            item.getResourceServer().getLoginUsername()));
    return dataSource;
}
 
Example #11
Source File: RepositoryConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DriverManagerDataSource getDataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
 
Example #12
Source File: RepositoryConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DriverManagerDataSource getDataSource() {
    final DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
 
Example #13
Source File: TestDataConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() {
	final DriverManagerDataSource ds = new DriverManagerDataSource();
	ds.setDriverClassName(driverClassName);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
	return ds;
}
 
Example #14
Source File: DataSourceConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Lazy
@Bean(name = {"one", "two", "dataSource"})
public DataSource dataSource() {
	DriverManagerDataSource ds = new DriverManagerDataSource();
	ds.setDriverClassName(driverClassName);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
	return ds;
}
 
Example #15
Source File: UserRepoDSConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
 
Example #16
Source File: UserRepoDSConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
 
Example #17
Source File: DataSourceConfig1.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource(@Value("#{dbProps.driverClassName}") String driverClassName,
		@Value("#{dbProps.url}") String url,
		@Value("#{dbProps.username}") String username,
		@Value("#{dbProps.password}") String password) {
	DriverManagerDataSource ds = new DriverManagerDataSource();
	ds.setDriverClassName(driverClassName);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
	return ds;
}
 
Example #18
Source File: DataSourceConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Lazy
@Bean(name = {"one", "two", "dataSource"})
public DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
 
Example #19
Source File: LocalDataSourceConfig.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * Returns local datasource
 * @return datasource
 */
@Bean
public DataSource localDataSource() {

	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	dataSource.setDriverClassName(driverClassName);
	dataSource.setUrl(url);
	dataSource.setUsername(userName);
	dataSource.setPassword(password);

	return dataSource;
}
 
Example #20
Source File: DataSourceConfig1.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource(@Value("#{dbProps.driverClassName}")String driverClassName,
                             @Value("#{dbProps.url}")String url,
                             @Value("#{dbProps.username}")String username,
                             @Value("#{dbProps.password}")String password) throws SQLException {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
 
Example #21
Source File: RepositoryConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public DriverManagerDataSource getDataSource() {
	final DriverManagerDataSource  ds = new DriverManagerDataSource();
	ds.setDriverClassName(driverClassName);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
	return ds;
}
 
Example #22
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void parametersSetWithList() {
	DataSource ds = new DriverManagerDataSource();
	operation.setDataSource(ds);
	operation.setSql("select * from mytable where one = ? and two = ?");
	operation.setParameters(new SqlParameter[] {
			new SqlParameter("one", Types.NUMERIC),
			new SqlParameter("two", Types.NUMERIC)});
	operation.afterPropertiesSet();
	operation.validateParameters(new Object[] { 1, "2" });
	assertEquals(2, operation.getDeclaredParameters().size());
}
 
Example #23
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void parameterPropagation() {
	SqlOperation operation = new SqlOperation() {};
	DataSource ds = new DriverManagerDataSource();
	operation.setDataSource(ds);
	operation.setFetchSize(10);
	operation.setMaxRows(20);
	JdbcTemplate jt = operation.getJdbcTemplate();
	assertEquals(ds, jt.getDataSource());
	assertEquals(10, jt.getFetchSize());
	assertEquals(20, jt.getMaxRows());
}
 
Example #24
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void compileTwice() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.setTypes(null);
	operation.compile();
	operation.compile();
}
 
Example #25
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void declareParameterAfterCompile() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.compile();
	exception.expect(InvalidDataAccessApiUsageException.class);
	operation.declareParameter(new SqlParameter(Types.INTEGER));
}
 
Example #26
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setTypeAfterCompile() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.compile();
	exception.expect(InvalidDataAccessApiUsageException.class);
	operation.setTypes(new int[] { Types.INTEGER });
}
 
Example #27
Source File: PersistenceXmlParsingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testExample4() throws Exception {
	SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
	DataSource ds = new DriverManagerDataSource();
	builder.bind("java:comp/env/jdbc/MyDB", ds);

	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example4.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement4", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("order-mappings.xml", info[0].getMappingFileNames().get(0));

	assertEquals(3, info[0].getManagedClassNames().size());
	assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0));
	assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1));
	assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2));

	assertTrue("Exclude unlisted should be true when no value.", info[0].excludeUnlistedClasses());

	assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType());
	assertEquals(0, info[0].getProperties().keySet().size());

	builder.clear();
}
 
Example #28
Source File: HibernateConfiguration.java    From butterfly with Apache License 2.0 5 votes vote down vote up
@Bean
public DriverManagerDataSource dataSource() {
    final DriverManagerDataSource source = new DriverManagerDataSource();
    source.setDriverClassName(this.driverClassName);
    source.setUsername(this.username);
    source.setPassword(this.password);
    source.setUrl(this.connectionUrl.replace('\\', '/'));

    return source;
}
 
Example #29
Source File: MysqlDatabaseManagementService.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteItem(ResourceItem item) {
    DriverManagerDataSource dataSource = newDatasource(item);
    try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();) {
        if (hasTables(connection, item.getName())) {
            throw new WecubeCoreException(String.format("Can not delete database [%s] : Database is not empty.", item.getName()));
        }
        mysqlAccountManagementService.deleteItem(item);
        statement.executeUpdate(String.format("DROP SCHEMA %s", item.getName()));
    } catch (SQLException e) {
        String errorMessage = String.format("Failed to delete schema [%s], meet error [%s].", item.getName(), e.getMessage());
        log.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
}
 
Example #30
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void validateInOutParameter() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("DUMMY_PROC");
	operation.declareParameter(new SqlOutParameter("DUMMY_OUT_PARAM", Types.VARCHAR));
	operation.declareParameter(new SqlInOutParameter("DUMMY_IN_OUT_PARAM", Types.VARCHAR));
	operation.validateParameters(new Object[] {"DUMMY_VALUE1", "DUMMY_VALUE2"});
}