JDBC 作为数据库访问的规范接口,其中只是定义一些接口。具体的实现是由各个数据库厂商来完成。
一、重要的接口:
1.public interface Driver 每个驱动程序类必须实现的接口。Java SQL 框架允许多个数据库驱动程序。每个驱动程序都应该提供一个实现 Driver 接口的类。DriverManager 会试着加载尽可能多的它可以找到的驱动程序,然后,对于任何给定连接请求,它会让每个驱动程序依次试着连接到目标 URL。强烈建议每个 Driver 类应该是小型的并且是单独的,这样就可以在不必引入大量支持代码的情况下加载和查询 Driver 类。在加载某一 Driver 类时,它应该创建自己的实例并向 DriverManager 注册该实例。这意味着用户可以通过调用以下程序加载和注册一个驱动程序
com.mysql.jdbc.Driver
- Class.forName("foo.bah.Driver")。例如:MYSQL驱动
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(newDriver());//注册驱动}catch (SQLException E) {
- throw newRuntimeException("Can't register driver!");
- }
- }
2. 通过查看 DriverManager 源码,我们也可以使用 System.setProperty("jdbc.drivers","....") 方式。
- String drivers;
- try {
- drivers = AccessController.doPrivileged(new PrivilegedAction() {
- 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(newPrivilegedAction() {
- public Void run() {
- ServiceLoaderloadedDrivers = ServiceLoader.load(Driver.class);
- IteratordriversIterator = 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;
- }
- });
来源: http://www.cnblogs.com/ljy-cloudy/p/7010753.html