不要重新发明轮子。Oracle 的 JDBC 驱动程序已经内置了这个功能。
这很有用:http ://www.orafaq.com/wiki/JDBC
import java.util.ArrayList;
import java.sql.*;
public class OracleConnection {
public static void main(String[] args) throws Exception {
//connect to database
Class.forName("oracle.jdbc.driver.OracleDriver");
ArrayList<String> serverNames = new ArrayList<String>();
serverNames.add("yourhostname1");
serverNames.add("yourhostname2");
serverNames.add("yourhostname3");
serverNames.add("yourhostname4");
String portNumber = "1521";
String sid = "ORCLSID";
String url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)" ;
for (String serverName : serverNames) {
url += "(ADDRESS=(PROTOCOL=tcp)(HOST="+serverName+")(PORT="+portNumber+"))";
}
url += ")(CONNECT_DATA=(SID="+sid+")))";
String username = "USERNAME";
String password = "PASSWORD";
// System.out.println(url); // for debugging, if you want to see the url that was built
Connection conn = DriverManager.getConnection(url, username, password);
}
}
上面的代码实际上构建和使用看起来像这样的 url(如下例所示)。我通过取消注释代码末尾附近的调试行明确地得到了这一点:
jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=
(LOAD_BALANCE=ON)(FAILOVER=ON)
(ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname1)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname2)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname3)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname4)(PORT=1521))
)(CONNECT_DATA=(SID=ORCLSID)))