Getting Database URL From JDBC Connection Object – 从JDBC连接对象中获取数据库URL

最后修改: 2020年 10月 16日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll discuss how we can get the database URL from a JDBC Connection object.

在这个快速教程中,我们将讨论如何从JDBC Connection对象中获取数据库URL。

2. Example Class

2.例证类

To demonstrate this, we’ll create a DBConfiguration class with a method getConnection:

为了证明这一点,我们将创建一个DBConfiguration类,其中有一个方法getConnection

public class DBConfiguration {

    public static Connection getConnection() throws Exception {
        Class.forName("org.h2.Driver");
        String url = "jdbc:h2:mem:testdb";
        return DriverManager.getConnection(url, "user", "password");
    }
}

3. The DatabaseMetaData#getURL Method

3.DatabaseMetaData#getURL方法

We can get the database URL by using the DatabaseMetaData#getURL method:

我们可以通过使用DatabaseMetaData#getURL方法获得数据库URL。

@Test
void givenConnectionObject_whenExtractMetaData_thenGetDbURL() throws Exception {
    Connection connection = DBConfiguration.getConnection();
    String dbUrl = connection.getMetaData().getURL();
    assertEquals("jdbc:h2:mem:testdb", dbUrl);
}

In the above example, we first obtain the Connection instance.

在上面的例子中,我们首先获得Connection实例。

Then, we call the getMetaData method on our Connection to get the DatabaseMetaData.

然后,我们在我们的Connection上调用getMetaData方法来获取DatabaseMetaData

Finally, we call the getURL method on the DatabaseMetaData instance. As we’d expect, it returns the URL of our database.

最后,我们在DatabaseMetaData实例上调用getURL方法。正如我们所期望的那样,它返回我们数据库的URL。

4. Conclusion

4.总结

In this tutorial, we’ve seen how we can get the database URL from the JDBC Connection object.

在本教程中,我们已经看到了如何从JDBC Connection对象中获取数据库URL。

As always, the complete code for this example is available over on GitHub.

一如既往,本例的完整代码可在GitHub上获得over