package manager;
import java.sql.Connection;
import java.sql.DriverManager;
public class OracleDriverManager
{
public Connection getConnection(String databaseURL, String userName, String password)
{
Connection ret = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
ret = DriverManager.getConnection(databaseURL, userName, password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return ret;
}
}
當程式需同時連接oracle 8i及oracle 11g而需不同的jdbc driver時,可另外用一個UrlClassLoader將舊的jdbc driver load進來,並將上面的class也load進與舊版jdbc driver同一個ClassLoader,再主程式用reflection的方式來使用OracleDriverManager去取得connection,如此才能讓DriverManager裡註冊的driver一致。
package tester;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import aic.Oracle8iManager;
public class Oracle8iTester {
/**
* @param args
*/
public static void main(String[] args) {
new Oracle8iTester().test();
}
private void test() {
String driverClassName = "oracle.jdbc.driver.OracleDriver";
String orclURL = "jdbc:oracle:thin:@localhost:1521:orcl";//11g
String ora8iURL = "jdbc:oracle:thin:@ora8ihost:1521:ora8i";//8i
String userName = "apps";
String password = "apps";
try {
Connection ora8iConn = Oracle8iManager.getInstance().getConnection(ora8iURL, userName, password);
println(ora8iConn);
testConnection(ora8iConn);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName(driverClassName);
Connection orclConn = DriverManager.getConnection(orclURL, userName, password);
println(orclConn);
testConnection(orclConn);
} catch (Exception e) {
e.printStackTrace();
}
}
private void testConnection(Connection conn) throws Exception {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT 'success' FROM dual");
String str = null;
if (resultSet.next()) {
str = resultSet.getString(1);
}
resultSet.close();
statement.close();
conn.close();
println(str);
}
private void println(Object o) {
System.out.println(o);
}
}