如果数据库不在本地主机,必须在$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)
)
)';