简体   繁体   中英

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.

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

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    
        }    
      }    
    }            
  }    
}

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)))

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.

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.

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

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

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

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

" ... 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM