0

I know how to connect to a database in usual way. What I need is to choose what database to connect at runtime.

I have a default database (used by the system) and many other options to user choose to aquire data. It implies in have no Entities or JPA mappings any way.

In older times I was using this:

  try (Connection connection = DriverManager.getConnection(connectionString, user, password);
  PreparedStatement preparedStatement = connection.prepareStatement(nativeQuery)) {

  preparedStatement.setString( 1, coordinate );

  try (ResultSet resultSet = preparedStatement.executeQuery()) {
    while (resultSet.next())
       result = resultSet.getString(RESULT_PARAM);
    }
  } catch (SQLException ex) {
    CodeUtils.log(QUERY_ERROR_MSG, this);
    CodeUtils.log(ex.getMessage(), this);
  }

But I don't know how to port this to Spring Boot.

Magno C
  • 1,922
  • 4
  • 28
  • 53
  • Never mind. I found this: https://stackoverflow.com/questions/52845453/creating-a-java-sql-connection-using-jdbc-and-spring-boot. Sorry. – Magno C Sep 10 '19 at 13:31

1 Answers1

0

You can define database configuration as below-

@Configuration
public class MyDBConfig {
    @Bean("db1Ds")
    @Primary
    @ConfigurationProperties("app.ds.db1")
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("db2Ds")
    @ConfigurationProperties("app.ds.db2")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("db1JdbcTemplate")
    @Autowired
    public JdbcTemplate db1JdbcTemplate(@Qualifier("db1Ds") DataSource ds) {
        return new JdbcTemplate(ds);
    }

    @Bean("db2JdbcTemplate")
    @Autowired
    public JdbcTemplate db2JdbcTemplate(@Qualifier("db2Ds") DataSource ds) {
        return new JdbcTemplate(ds);
    }
}

Switch the Jdbc template based on what user selects.

Official Doc: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-two-datasources

kann
  • 687
  • 10
  • 22
  • I can't do it. The user will decide wich database / server he will connect to. I'll not offer him a list of options like "you can connect to db1 or db2. The user will tell to system "connect to database URL/USER/PASSWORD and give me the JSON data for this query"...something like this. But this link solved the problem exactly what the way I need. https://stackoverflow.com/questions/52845453/creating-a-java-sql-connection-using-jdbc-and-spring-boot. I figured out there is no need to change anything what I've done before. – Magno C Sep 10 '19 at 17:23