Link to home
Start Free TrialLog in
Avatar of BarryMcGillin
BarryMcGillin

asked on

Getting db hostname and port number from a jdbc connection

Hi
I have a connection like this.
<code>
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
         conn = DriverManager.getConnection(
            "jdbc:oracle:thin:@devbox:1521:UTF", "test", "test");
</code>

and I want to find out the following information from the connection.   I can get some of the information I need, but not all of it and the javadocs are not much help getting this out.  I've looked at INetAddress, but this seems to give local hostnames, not the hostname and the port number of the database I am connected to.
<code>
   try {
        DatabaseMetadata metaData = conn.getMetaData();
        String URL metaData.getURL();
        String hostname = /* How do we do this? */
        int port = /* how do we do this? */
        String DBType = metaData.getDatabaseProductName();
        String username = metaData.getUserName();
       } catch (SQLException e) {
                e1.printStackTrace();
       }
</code>
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

The hostname and port are in the connection string:

hostname: devbox
port: 1521
Check this
http://www.princeton.edu/~storacle/jdbc8_doc/oracle.jdbc.pool.OracleDataSource.html

Looks like you can use
 getDatabaseName()

and
getPortNumber()
ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pankilmpatel
pankilmpatel

Avatar of BarryMcGillin

ASKER

These dont seem to work.  I'm wondering why this doesn't work either.
If we get back a URL, surely then creating a standard java.net.URL will be able to pull it out.
<code>
 try {
           connURL = new URL(metaData.getURL());
      } catch (MalformedURLException e) {
          e.printStackTrace();
      }
       String host = connURL.getHost();
       int port = connURL.getPort());
</code>
Unfortunately I'm getting this.....
<exception>
java.net.MalformedURLException: unknown protocol: jdbc
      at java.net.URL.<init>(URL.java:574)
      at java.net.URL.<init>(URL.java:464)
      at java.net.URL.<init>(URL.java:413)
</exception>
java.net.URL is not for JDBC URLs. It is for web-like URLs that are on HTTP, etc.