时间:2021-07-01 10:21:17 帮助过:22人阅读
Class.forName("foo.bah.Driver")。例如:MYSQL驱动
com.mysql.jdbc.Driver
2.public interface Connection 与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。
3.public interface Statement 用于执行静态 SQL 语句并返回它所生成结果的对象。
4.public interface PreparedStatement 表示预编译的 SQL 语句的对象。SQL 语句被预编译并存储在 PreparedStatement
对象中。然后可以使用此对象多次高效地执行该语句。
二、驱动的加载方式
1.最常用的是使用 Class.forName("com.mysql.jdbc.Driver");方式。这行代码只是使用当前的类加载去加载具体的数据库驱动,不要小看这简单的这一行代码。在Driver类中的static域中把当前驱动注册到DriverManager中。
static { try { java.sql.DriverManager.registerDriver(new Driver());//注册驱动 } catch (SQLException E) { throw new RuntimeException("Can‘t register driver!"); } }
2.通过查看DriverManager源码,我们也可以使用System.setProperty("jdbc.drivers","....")方式。
String drivers;
try {
drivers = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.getProperty("jdbc.drivers");
}
});
} catch (Exception ex) {
drivers = null;
}
String[] driversList = drivers.split(":");
println("number of Drivers:" + driversList.length);
for (String aDriver : driversList) {
try {
println("DriverManager.Initialize: loading " + aDriver);
Class.forName(aDriver, true,
ClassLoader.getSystemClassLoader());
} catch (Exception ex) {
println("DriverManager.Initialize: load failed: " + ex);
}
}
3.最直接(不推荐)方式new com.mysql.jdbc.Driver();
4.为了更好的使用数据库驱动,JDBC为我们提供了DriverManager类。如果我们都没有使用以上方式,DriverManager初始化中会通过ServiceLoader类,在我们classpath中jar(数据库驱动包)中查找,如存在META-INF/services/java.sql.Driver文件,则加载该文件中的驱动类。
AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); Iterator<Driver> driversIterator = loadedDrivers.iterator(); /* Load these drivers, so that they can be instantiated. * It may be the case that the driver class may not be there * i.e. there may be a packaged driver with the service class * as implementation of java.sql.Driver but the actual class * may be missing. In that case a java.util.ServiceConfigurationError * will be thrown at runtime by the VM trying to locate * and load the service. * * Adding a try catch block to catch those runtime errors * if driver not available in classpath but it‘s * packaged as service and that service is there in classpath. */ try{ while(driversIterator.hasNext()) { driversIterator.next(); } } catch(Throwable t) { // Do nothing } return null; } });
JDBC加载数据库驱动的方式
标签:自己的 exception site 常用 errors trying 初始化 源码 color