Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE

1. Overview

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

2. Example Class

To demonstrate this, we'll create a DBConfiguration class with a method 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

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

@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.

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

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

4. Conclusion

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

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

Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
Comments are closed on this article!