nigel thomas nigel thomas - 1 year ago 305
Java Question

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

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

Answer Source

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