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.
... // jdbc:oracle:thin:@<hostname>:<port>:<sid> String url = "jdbc:oracle:thin:@GalacticAC:1521:xe"; ... and it worked.
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
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.
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