當前位置:編程學習大全網 - 源碼下載 - Java加載數據庫連接驅動,為什麽要用Class.forName()方法?

Java加載數據庫連接驅動,為什麽要用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); 。因此壹般情況下,對於程序員來說,除非特別需求,是不會自己去實例化壹個數據庫驅動使用裏面的方法的。

  • 上一篇:請問壹下非洲的地理知識
  • 下一篇:學習python爬蟲推薦書籍
  • copyright 2024編程學習大全網