Parsing Database URL with Java

This is my first blog posting. I am a software developer and find that I spend a lot of time looking for information, but don’t contribute once I actually find stuff. So I’m going to start blogging about what I’ve learned…let it be trivial, or complex.

On that note. I’ve come across the problem of parsing a jdbc URL in Java.
Basically I’m given a URL in the format
jdbc:db2://HOST:50001/SERVER:variable=30;

I was trying to write regular expressions to parse this, but got VERY complicated when I found DB2 does it different thank SQL who does it different than Oracle, and so on.

So I heard I could use Java URI.

URI uri = new URI(“jdbc:db2://HOST:50001/SERVER:variable=30”);
System.out.println(“Port = ” + uri.getPort());
System.out.println(“Host = ” + uri.getHost());
System.out.println(“Path = ” + uri.getPath());

Output :
Port = -1
Host = null
Path = null

So that sucked didn’t work…I dug a little further

What you also need to do is strip off the jdbc: from the start.
URI uri = new URI(“jdbc:db2://HOST:50000/SERVER:variable=30″);
System.out.println(“Port = ” + uri.getPort());
System.out.println(“Host = ” + uri.getHost());
System.out.println(“Path = ” + uri.getPath());

Output :
Port =50000
Host = HOST
Path = /SERVER:variable=30

So yay it worked.

I’m sure there’s an advanced way to do this, but I didn’t need to bother after this point.

Anyways, I hope this has helped someone along the way. Let me know if this was useful to you, or if you have any other ideas of how to do this.

Leave a comment