Partner – DBSchema – NPI (tag = SQL)
announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

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 {
        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:

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.

Course – LSD (cat=Persistence)

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

res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.