1. 程式人生 > 實用技巧 >JDBC4.0版本後,不用再顯式註冊驅動

JDBC4.0版本後,不用再顯式註冊驅動

一般寫JDBC程式碼的時候都會有這麼一句程式碼:

1 Class.forName("com.mysql.jdbc.Driver");

這是載入資料庫的註冊驅動。但是從JDBC4.0後,就不用顯式載入了,也就是人家DriverManager類自動幫你載入了,這句程式碼你不用寫了,直接獲取資料庫連線就行

可以看下:java.sql.DriverManager 類中的註釋:

*<P> The <code>DriverManager</code> methods <code>getConnection</code> and
 * <code>getDrivers</code> have been enhanced to support the Java Standard Edition
 
* <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">Service Provider</a> mechanism. JDBC 4.0 Drivers must * include the file <code>META-INF/services/java.sql.Driver</code>. This file contains the name of the JDBC drivers * implementation of <code>java.sql.Driver</code>. For example, to load the <code>my.sql.Driver</code> class, * the <code>META-INF/services/java.sql.Driver</code> file would contain the entry:
* <pre> * <code>my.sql.Driver</code> * </pre> * * <P>Applications no longer need to explicitly load JDBC drivers using <code>Class.forName()</code>. Existing programs * which currently load JDBC drivers using <code>Class.forName()</code> will continue
to work without * modification. <P>When the method <code>getConnection</code> is called, * the <code>DriverManager</code> will attempt to * locate a suitable driver from amongst those loaded at * initialization and those loaded explicitly using the same classloader * as the current applet or application.

著重看這一句話:

1 * <P>Applications no longer need to explicitly load JDBC drivers using <code>Class.forName()</code>. Existing programs
2  * which currently load JDBC drivers using <code>Class.forName()</code> will continue to work without
3  * modification.

上面的註釋的意思就是說,JDBC4.0後必須包含:the file <code>META-INF/services/java.sql.Driver</code>這個檔案,並且檔案中必須有如下程式碼:

<code>my.sql.Driver</code>

我看了下我資料庫jar包下對應的目錄,確實有這個檔案,而這個檔案的內容確實有這段程式碼:

在獲取連線的時候,會自動的查詢合適的驅動類,並初始化當前使用相同驅動的類。

所以啊,就不勞我們費心自己手動載入註冊驅動了:Class.forName("com.mysql.jdbc.Driver);不寫也罷,當然,你想寫也可以加上。