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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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. stackoverflow.com/questions/52845453/…. I figured out there is no need to change anything what I've done before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.