How to connect to remote database through DB link using JDBC?

Nigel Thomas picture Nigel Thomas · Jun 20, 2012 · Viewed 14.2k times · Source

I need to connect to a remote database using Database link using JDBC commands. How can it be done?

Answer

jarhed picture jarhed · Jun 20, 2012

If you already have the dblink setup, you can utilize it in your SQL (sent via jdbc) by addressing the required tables like such:

select * from SCHEMA.TABLE@DBLINK_NAME

Using this query inside of your java would look something like this

    public ResultSet execQuery() throws SQLException, ClassNotFoundException{
    //Load the database driver
    Class.forName("oracle.jdbc.OracleDriver");

    //Create connection to the database
    Connection myConnection = DriverManager.getConnection(connectURL,userName,userPwd);

    //Create a statement link to the database for running queries
    Statement myQuery = myConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

    //Create a resultSet to hold the returned query information
    ResultSet myQueryResults = myQuery.executeQuery("select * from SCHEMA.TABLE@DBLINK_NAME");       

    return myQueryResults;
}

*java & oracle assumed