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?
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?
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}