简体   繁体   中英

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM