1

In my application using different databases (postgres, mssql, oracle ...). What is the best way to get database name use metadata. I was trying to use this approach:

try (final Connection connection = jdbcTemplate.getDataSource().getConnection()) {
    final DatabaseMetaData metaData = connection.getMetaData();
    final String databaseName = StringUtils.substringAfterLast(connection.getMetaData().getURL(), "/");

It works in this case:

spring.datasource.url=jdbc:mysql://localhost:3306/2022_2

But in this case it doesn't work:

spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=test_mssql;encrypt=true;trustServerCertificate=true;

1 Answer 1

3

You may consider using Connection#getCatalog() for your case.

Please see the following example below:

try (final Connection connection = jdbcTemplate.getDataSource().getConnection()) {
    String databaseName = connection.getCatalog();
} catch (SQLException e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

Comments

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.