如何动态的加载这些驱动!不可能把所有的数据库驱动都集成到JAR包中吧?!于是动态加载驱动的JAR包就产生了!其实这些在做系统基础代码时,经常用到,只是一般我们没有机会去搞而已。
动态加载JAR包,使用JAR包里的类,代码如下:
package org; import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties; public class Test
{
public static void main(String[] args) throws Exception
{
File file = new File("/root/workspace/RPT2.9SP1/WebContent/WEB-INF/lib/ojdbc14.jar");
URLClassLoader loader = new URLClassLoader(new URL[] { file.toURI().toURL() });
Class clazz = loader.loadClass("oracle.jdbc.driver.OracleDriver");
Driver driver = (Driver) clazz.newInstance();
Properties p = new Properties();
p.put("user", "newrpt_plt");
p.put("password", "newrpt_plt");
Connection con = driver.connect("jdbc:oracle:thin:@10.0.1.204:1521:lgdnew", p);
System.out.println(con);
//获取系统URLClassLoader
URLClassLoader classloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
//获取一个新建类的方法
Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
}
}