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方法的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM