What is the best way to get database name use java metadata

Viewed 33

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 Answers

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();
}
Related