JDBC加载数据库驱动的⽅式
  JDBC作为数据库访问的规范接⼝,其中只是定义⼀些接⼝。具体的实现是由各个数据库⼚商来完成。
  ⼀、重要的接⼝:
  1.public interface Driver 每个驱动程序类必须实现的接⼝。Java SQL 框架允许多个数据库驱动程序。每个驱动程序都应该提供⼀个实现 Driver 接⼝的类。DriverManager 会试着加载尽可能多的它可以到的驱动程序,然后,对于任何给定连接请求,它会让每个驱动程序依次试着连接到⽬标 URL。强烈建议每个 Driver 类应该是⼩型的并且是单独的,这样就可以在不必引⼊⼤量⽀持代码的情况下加载和查询 Driver 类。在加载某⼀ Driver 类时,它应该创建⾃⼰的实例并向 DriverManager 注册该实例。这意味着⽤户可以通过调⽤以下程序加载和注册⼀个驱动程序  Class.forName("foo.bah.Driver")。例如:MYSQL驱动sql.jdbc.Driver
  2.public interface Connection 与特定数据库的连接(会话)。在连接上下⽂中执⾏ SQL 语句并返回结果。
  3.public interface Statement ⽤于执⾏静态 SQL 语句并返回它所⽣成结果的对象。
  4.public interface PreparedStatement 表⽰预编译的 SQL 语句的对象。SQL 语句被预编译并存储在 Pre
paredStatement 对象中。然后可以使⽤此对象多次⾼效地执⾏该语句。java的jdbc连接数据库
  ⼆、驱动的加载⽅式
  1.最常⽤的是使⽤ Class.forName("sql.jdbc.Driver");⽅式。这⾏代码只是使⽤当前的类加载去加载具体的数据库驱动,不要⼩看这简单的这⼀⾏代码。在Driver类中的static域中把当前驱动注册到DriverManager中。
static {
try {
java.isterDriver(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() {
Property("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,
} catch (Exception ex) {
println("DriverManager.Initialize: load failed: " + ex);
}
}
  3.最直接(不推荐)⽅式sql.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()) {
<();
}
} catch(Throwable t) {
// Do nothing
}
return null;
}
});