1

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?

gillesB
  • 1,061
  • 1
  • 14
  • 30

1 Answers1

3

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}

gillesB
  • 1,061
  • 1
  • 14
  • 30
  • 1
    I'm curious, what will this do with multi-host URLs (see https://jdbc.postgresql.org/documentation/head/connect.html under _Connection Fail-over_ near the end)? – Mark Rotteveel Jan 09 '21 at 13:49
  • Thank you for your comment, I did not know about fail-over hosts. I enhanced the answer accordingly. – gillesB Jan 10 '21 at 15:09