Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test connection to Oracle Database using Java

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.

like image 992
Bimbz Avatar asked Sep 12 '13 05:09

Bimbz


People also ask

What is the JDBC URL for Oracle?

... // jdbc:oracle:thin:@<hostname>:<port>:<sid> String url = "jdbc:oracle:thin:@GalacticAC:1521:xe"; ... and it worked.


2 Answers

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
like image 112
Subhrajyoti Majumder Avatar answered Sep 27 '22 21:09

Subhrajyoti Majumder


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.

like image 41
RogerIsDead Avatar answered Sep 27 '22 22:09

RogerIsDead