18

Is there a way to test my connection to oracle database using Java? Here's my code.

public class OracleConnection {

    public static void main(String[] args) throws Exception {
        //connect to database
        Class.forName("oracle.jdbc.driver.OracleDriver");
        String serverName = "00.000.0.000";
        String portNumber = "1521";
        String sid = "My Sid";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String username = "UNAME";
        String password = "PASSWORD";
        Connection conn = DriverManager.getConnection(url, username, password);
    }
}

What I want to do is test the database if it is reachable and if its not then the program will connect to the next database. I have 8 production database.

4
  • You should basically try to connect to one database on one IP and if the connection object is null.... then try to Connect to another.... maybe the connection code should be a recursive call till you get a valid connection Commented Sep 12, 2013 at 6:03
  • but it returns an exception and then it will stop. :( Commented Sep 16, 2013 at 8:07
  • yes you need to handle the exception and call the recursive function again from the catch block Commented Sep 16, 2013 at 8:15
  • It's also not working. I cannot understand why I've tried "try catch" but still it will stop working. Commented Sep 16, 2013 at 9:38

10 Answers 10

22

DriverManager#getConnection it self attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers. and thorws SQLException if a database access error occurs.

you can test you connection is valid or not with Connection#isValid(int timeout) returns true if the connection has not been closed and is still valid.

...
Connection conn = DriverManager.getConnection(url, username, password);
boolean reachable = conn.isValid(10);// 10 sec
Sign up to request clarification or add additional context in comments.

8 Comments

It says "The method IsValid() is undefined for the type connection?
Connection#isValid method is available with Connection class since java 1.6. What jdk version you are using?
I see my JDK is still 1.4 hahahaha!! I'll update my JDK first. Thanks!!
will it affect anything on my codes or applications or anything on my machine if I change my JDK? like will eclipse reset? sorry for that very noobish question but I am really a newbie in java. hahaha thanks
catch the exception, what I mean is DriverManager#getConnection throws SQLException, hadle this exception properly...
|
10

Don't reinvent the wheel. Oracle's JDBC driver already has this functionality built-in.

This is useful: http://www.orafaq.com/wiki/JDBC

import java.util.ArrayList;
import java.sql.*;

public class OracleConnection {

    public static void main(String[] args) throws Exception {
        //connect to database
        Class.forName("oracle.jdbc.driver.OracleDriver");
        ArrayList<String> serverNames = new ArrayList<String>();
        serverNames.add("yourhostname1");
        serverNames.add("yourhostname2");
        serverNames.add("yourhostname3");
        serverNames.add("yourhostname4");
        String portNumber = "1521";
        String sid = "ORCLSID";
        String url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)" ;
        for (String serverName : serverNames) {  
            url += "(ADDRESS=(PROTOCOL=tcp)(HOST="+serverName+")(PORT="+portNumber+"))";
        }
        url += ")(CONNECT_DATA=(SID="+sid+")))";
        String username = "USERNAME";
        String password = "PASSWORD";
        // System.out.println(url); // for debugging, if you want to see the url that was built
        Connection conn = DriverManager.getConnection(url, username, password);
    }
}

The above code actually builds and uses url that looked like this (as example belows). I got this explicitly by uncommenting the debugging line near the end of the code:

jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=
    (LOAD_BALANCE=ON)(FAILOVER=ON)
    (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname1)(PORT=1521))
    (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname2)(PORT=1521))
    (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname3)(PORT=1521))
    (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname4)(PORT=1521))
  )(CONNECT_DATA=(SID=ORCLSID)))

Comments

10

Simple Java code to check connection to Oracle DB:

import java.sql.*;    
public class Test {
  private final static String DB_URL = "jdbc:oracle:thin:@//192.168.1.105:1521/MYORA";
  private final static String USER = "myuser";
  private final static String PASS = "mypwd";

  public static void main(String[] args) {
    Connection conn = null;  
    try {    
      Class.forName("oracle.jdbc.driver.OracleDriver");    
      System.out.println("Connecting to database...");    
      conn = DriverManager.getConnection(DB_URL,USER,PASS);    
    } catch (Exception e) {    
      e.printStackTrace();    
    } finally {    
      if (conn != null) {    
        try {    
          conn.close();    
        } catch (SQLException e) {    
          // ignore    
        }    
      }    
    }            
  }    
}

3 Comments

Upvote for providing a very use example on constructing connection url.
Works like a charm. Just need to add the lib reference to ojdbc6.jar as described in stackoverflow.com/questions/17803818/…
This url doesn't work for me. I referred over here docs.oracle.com/cd/E11882_01/appdev.112/e13995/oracle/jdbc/… . I had to replace / with colon(:)
3

I wrote a mini command line app to do what above code samples do.

https://github.com/aimtiaz11/oracle-jdbc-tester

Saves anyone coding it up. Just build (with maven) and run it.

Comments

0

You can have an array of the your database server ips and iterate over them. For every failed connection attempt, you can proceed to the next ip from the array and try again. In case of a successful connection, you break the loop there and use the current connection which was established.

Comments

0

Maybe you should ping the IP address of the server. You should check this out: Ping function returns that all pinged IP addresses is reachable

Comments

0

You can catch SQLException from DriverManager.getConnection() and looks for ORA-12543.
Read SQLException documentation about vendor code.

Comments

0
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(“url”,”username”,”password ″); 

look more at here:http://leezk.com/tag/jdbc

Comments

0

"... and if its not then the program will connect to the next ..." I wonder if a cluster connection string containing multiple server addresses could work for you. (I did not try this myself.) Look at Oracle Connection String for RAC Environment.

Comments

0

For testing connection i will create and use 2 methods: for connection to db and for test this connection:

Class Connector {
private static final String CONNECTION_STRING = "jdbc:oracle:thin:@//%s:%d/%s";
private static final String QUERY_IS_CONNECTED = "SELECT * FROM table WHERE field = 'example'";
private static final Log LOG = LogFactory.getLog(Connector.class);

public Connection createConnection() {
    Connection connection = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        connection = DriverManager.getConnection(String.format(CONNECTION_STRING, "127.0.0.1", "1521", "dbName"), "userName", "password");
    } catch (Exception e) {
        LOG.error("createConnection: connection error");
    }

 return connection;
}

public boolean isConnected() {

        try (Connection connection = createConnection()) {
            if (connection.isClosed()) {
                    return false;
            }

            try (Statement statement = connection.createStatement();
                 ResultSet resultSet = statement.executeQuery(QUERY_IS_CONNECTED)) {
                if (resultSet == null) {
                    return false;
                }
            } catch (Exception e) {
                LOG.error("isConnected: Query error", e);
                return false;
            }
        } catch (Exception e) {
            LOG.error("isConnected: Check connection error", e);
            return false;
        }

        return true;
    }
}

createConnection() - default connection to your db. Values of ip,port,dbName,userName and password will be yours.

isConnected() - first part check correct your connection and second part checks the correctness of working with the database. As there can be a connection, but not to be access for requests.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.