Adam
Adam

Reputation: 615

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

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;

Upvotes: 1

Views: 1135

Answers (1)

Alexander Golovnya
Alexander Golovnya

Reputation: 321

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

Upvotes: 3

Related Questions