使用
11gr2
新组件
scan 方式连接(假设scan_vip为192.168.100.217)
String url = "jdbc:oracle:thin:@192.168.100.217:1521/prod"
也可以使用
11gr2
以前
vip
方式连接
String url
=
"jdbc:oracle:thin:@(DESCRIPTION ="
+
"(ADDRESS_LIST ="
+
"(ADDRESS=(PROTOCOL=TCP)(HOST=el1)(PORT=1521))"
+
"(ADDRESS=(PROTOCOL=TCP)(HOST=el2)(PORT=1521))"
+
"(LOAD_BALANCE = yes)"
+
")"
+
"(CONNECT_DATA="
+
"(SERVER=DEDICATED)"
+
"(SERVICE_NAME=prod )"
+
")"
+
")"
;
注:
jdbc thin
使用
11gr2
以前
vip
方式连接,
host
中不可以直接使用
ip
,否则会出现NL Exception was generated 错误。需要使用别名。并且在
hosts
文件中定义。
例如本例中两台机器的
vip
为
192.168.100.123
和
192.168.100.124
并且,别名为
el1
,
el2
。那么在
hosts
文件中需要有下面两行
192.168.100.123 el1
192.168.100.124 el2
host
文件位置:
linux|unix:/etc/hosts
windows:$
系统盘
\WINDOWS\system32\drivers\etc\hosts
下面是一个完整的实例:
package jdbc.dex.com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class JDBC1 {
public static void main(String[] args){
String urlVip = "jdbc:oracle:thin:@(DESCRIPTION ="
+ "(ADDRESS_LIST ="
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=el1)(PORT=1521))"
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=el2)(PORT=1521))"
+ "(LOAD_BALANCE = yes)"
+ ")" + "(CONNECT_DATA=" + "(SERVER=DEDICATED)"
+ "(SERVICE_NAME=prod )" + ")" + ")";
String urlScan1="jdbc:oracle:thin:@(DESCRIPTION ="+
"(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.100.217)(PORT = 1521))"+
"(CONNECT_DATA ="+
"(SERVER = DEDICATED)"+
"(SERVICE_NAME = prod)"+
")"+
")";
String urlScan2="jdbc:oracle:thin:@192.168.100.217:1521/prod" ;
String driver="oracle.jdbc.driver.OracleDriver" ;
Connection con ;
Statement st ;
ResultSet rs ;
try {
Class.forName(driver) ;
con = DriverManager.getConnection(urlVip,"dexter","xiaojun");
st=con.createStatement() ;
rs=st.executeQuery("select 2 from dual ") ;
while(rs.next()) {
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}