如果數據庫不在本地主機,必須在$Oracle_HOME/network/admin/tnsnames.ora中配置相應的tns,然後程序才能通過配置好的tns訪問數據庫,但是Java通過thin方式訪問Oracle例外,可以采用在本地配置好的tns別名,也可以采用tns全解析名,采用別名等號後的全描述符;如下:
TESTCZ =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.70.9.12)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = TESTCZ)
)
)
舉例。
現在有兩個數據庫
adb,用戶名和密碼分別是adb/adb,在本地主機配置的tns名字是tns_a,所在主機a;
bdb,用戶名和密碼分別是bdb/bdb,在本地主機配置的tns名字是tns_b,所在主機b;
現在需要在adb上面建一個連接到bdb數據庫的dblink;
方法1:
在a主機上編輯tnsnames.ora文件配置bdb數據庫的tns別名tns_b,如下:
tns_b =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.70.9.12)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = dbtestb)
)
)
然後創建數據庫連接,如下:
create database linkconnect to bdb identified by identifIEd by bdb
using 'tns_b';
方法2:
如果沒有權限修改tnsnames.ora,那麼就沒有辦法建立到adb數據庫的tns別名,那麼就只能采用在創建dblink的時候,全寫解析符號。創建dblink的方法如下:
create database link
connect to bdb identified by identifIEd by bdbusing '(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.70.9.12)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = dbtestb)
)
)';
創建好tns別名之後,可以采用sqlplus username/passWord@tnsname來測試創建的tns別名是否正確。
我在生產系統中創建的一個dblink示例:
create database link NEW_DBLINK
connect to AIIPS identifIEd by "1qaz2wsx"
using '(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.70.193.12)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = zjpub)
)
)';