How can I parse a JDBC URL (oracle or sqlserver) to get the hostname, port, and database name. The formats of the URL are different.
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.
The default port is 1433, but SQL Server can be configured at product installation to listen on any port. Make sure that SQL Server is listening on port 1433. Or, if the port has been changed, make sure that the port specified in the JDBC connection URL matches the changed port.
jdbc:mysql://myhost1:3306,myhost2:3307/db_name. jdbc:mysql://[myhost1:3306,myhost2:3307]/db_name.
Start with something like this:
String url = "jdbc:derby://localhost:1527/netld;collation=TERRITORY_BASED:PRIMARY"; String cleanURI = url.substring(5); URI uri = URI.create(cleanURI); System.out.println(uri.getScheme()); System.out.println(uri.getHost()); System.out.println(uri.getPort()); System.out.println(uri.getPath());
Output from the above:
derby localhost 1527 /netld;collation=TERRITORY_BASED:PRIMARY
That didn't work for me. I came up with these methods, based on the assumption that hostname and port are always joined together by a colon. That assumption holds for all the databases I have to deal with at work (Oracle, Vertica, MySQL, etc). But it probably don't work for something that doesn't reach out to a network port.
String url = null; // set elsewhere in the class final public String regexForHostAndPort = "[.\\w]+:\\d+"; final public Pattern hostAndPortPattern = Pattern.compile(regexForHostAndPort); public String getHostFromUrl() { Matcher matcher = hostAndPortPattern.matcher(url); matcher.find(); int start = matcher.start(); int end = matcher.end(); if(start >= 0 && end >= 0) { String hostAndPort = url.substring(start, end); String [] array = hostAndPort.split(":"); if(array.length >= 2) return array[0]; } throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'"); } public int getPortFromUrl() { Matcher matcher = hostAndPortPattern.matcher(url); matcher.find(); int start = matcher.start(); int end = matcher.end(); if(start >= 0 && end >= 0) { String hostAndPort = url.substring(start, end); String [] array = hostAndPort.split(":"); if(array.length >= 2) return Integer.parseInt(array[1]); } throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With