3

What is the best way to parse a Postgresql JDBC URL to get the hostname, port and database name.

This is a specific case of this question: How to parse a JDBC url to get hostname,port etc?

1 Answer 1

4

A possibility is to use the Postgresql JDBC driver to parse the URL. This works, of course, only if it is a Postgresql URL.

If the provided URL contains no fail-over host the following can be done:

Properties props = org.postgresql.Driver.parseURL("jdbc:postgresql:myDatabase", null);

String host   = props.getProperty(PGProperty.PG_HOST.getName());
int    port   = Integer.parseInt(props.getProperty(PGProperty.PG_PORT.getName()));
String dbName = props.getProperty(PGProperty.PG_DBNAME.getName());

The above call returns the following properties: {PGDBNAME=myDatabase, PGPORT=5432, PGHOST=localhost}

If the URL contains fail-over hosts the host property and port property contain multiple, comma-separated values. For example the call

Properties props = org.postgresql.Driver.parseURL("jdbc:postgresql://host1:5434,host2:5433/database", null);

will return the following properties: {PGDBNAME=database, PGPORT=5434,5433, PGHOST=host1,host2}

Sign up to request clarification or add additional context in comments.

3 Comments

I'm curious, what will this do with multi-host URLs (see jdbc.postgresql.org/documentation/head/connect.html under Connection Fail-over near the end)?
Thank you for your comment, I did not know about fail-over hosts. I enhanced the answer accordingly.
this fails with testcontainer url: jdbc:tc:postgresql:latest:///testdatabase isnt there a general purpose jdbc parser?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.