• jdbc中Class.forName(driverName)的作用


    Class.forName有一个装载类对象的作用。装载就包括了初始化的操作。

    Driven中的代码:

    复制代码
    public class Driver extends NonRegisteringDriver implements java.sql.Driver {
        public Driver() throws SQLException {
        }
    
        static {
            try {
                DriverManager.registerDriver(new Driver());
            } catch (SQLException var1) {
                throw new RuntimeException("Can't register driver!");
            }
        }
    }
    复制代码

    JDBC规范要求Driver类在使用前必须向DriverManger注册自己。注册过程在Driver类的静态类已经实现。也就是说只要类被加载,就完成了向驱动管理器的注册。

    Java开发特别是数据库开发中,经常会用到Class.forName( )这个方法。通过查询Java Documentation我们会发现使用Class.forName( )静态方法的目的是为了动态加载类。在加载完成后,一般还要调用Class下的newInstance( )静态方法来实例化对象以便操作。因此,单单使用Class.forName( )是动态加载类是没有用的,其最终目的是为了实例化对象。
    Class.forName("")返回的是类
    Class.forName("").newInstance()返回的是object
    刚才提到,Class.forName("");的作用是要求JVM查找并加载指定的类,如果在类中有静态初始化器的话,JVM必然会执行该类的静态代码 段。而在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,即任何一个JDBC Driver的 Driver类的代码都必须类似如下:
    public class MyJDBCDriver implements Driver {static {DriverManager.registerDriver(new MyJDBCDriver());}}既然在静态初始化器的中已经进行了注册,所以我们在使用JDBC时只需要Class.forName(XXX.XXX);就可以了。
    we just want to load the driver to jvm only, but not need to user the instance of driver, so call Class.forName(xxx.xx.xx) is enough, if you call Class.forName(xxx.xx.xx).newInstance(), the result will same as calling Class.forName(xxx.xx.xx), because Class.forName(xxx.xx.xx).newInstance() will load driver first, and then create instance, but the instacne you will never use in usual, so you need not to create it.总结:jdbc数据库驱动程序最终的目的,是为了程序员能拿到数据库连接,而进行jdbc规范的数据库操作。拿到连接的过程是不需要你自己来实例化驱动程序的,而是通过 DriverManger.getConnection(string str); 。因此一般情况下,对于程序员来说,除非特别需求,是不会自己去实例化一个数据库驱动使用里面的62616964757a686964616fe78988e69d8331333332636366方法的。

  • 相关阅读:
    tcpip数据包编码解析(chunk and gzip)_space of Jialy_百度空间
    epoll 事件之 EPOLLRDHUP
    c What is the Difference Between read() and recv() , and Between send() and write()? Stack Overflow
    HTTP KeepAlive详解 IT心雪的日志 网易博客
    北京生活 TIPS 银行服务篇
    eventfdaiotest.c
    北京生活 TIPS 谈谈日常理财
    C语言抓http gzip包并解压 失败 C/C++ ChinaUnix.net
    转:javascript 对象和原型
    转:Javascript原型链和原型的一个误区
  • 原文地址:https://www.cnblogs.com/huhewei/p/13035124.html
Copyright © 2020-2023  润新知