简体   繁体   中英

Connect to an external Oracle DB using TNS

I need to connect to an external database to copy data from there to my table. I have a TNS file for this external database, and I am trying to connect using JDBC like this:

try {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
                        host +
                        ")(PORT=" +
                        port +
                        ")))(CONNECT_DATA=(SERVICE_NAME=" +
                        service +
                        ")))",
                    user,
                    password);
...


But when trying to connect, i get the error java.net.UnknownHostException (host is not recognized). I guess the problem is that this is an internal host and I don't have access to it. How to connect to the database using TNS?

You should not need the full TNS text. The following should suffice

getConnection("jdbc:oracle:thin:myuser/mypass@//"+host+":"+port+"/"+service);

If you have a tnsnames.ora then, you can provide the TNS alias as part of your connection string. Make sure you try to login to the Oracle Database through sqlplus using the connection string present in tnsnames.ora.

// dbname_tnsalias - It is the TNS alias present in tnsnames.ora.
 // TNS_ADMIN --> Absolute path where tnsnames.ora is present. 
 final String DB_URL="jdbc:oracle:thin:@dbname_tnsalias?TNS_ADMIN=/Users/test/";

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