日期:2014-05-20  浏览次数:20745 次

JDBC的注册驱动的问题,有一些不了解。
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// ~ Static fields/initializers
// ---------------------------------------------

//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}

// ~ Constructors
// -----------------------

/**
 * Construct a new driver and register it with DriverManager
 * 
 * @throws SQLException
 *             if a database error occurs.
 */
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}



上面是com.mysql.jdbc.Driver的源代码。

通常,我们通过如下的语句进行驱动注册:
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
这个方法的代码如下:

 public static synchronized void registerDriver(java.sql.Driver driver)
        throws SQLException {

        /* Register the driver if it has not already been added to our list */
        if(driver != null) {
            registeredDrivers.addIfAbsent(new DriverInfo(driver));
        } else {
            // This is for compatibility with the original DriverManager
            throw new NullPointerException();
        }

        println("registerDriver: " + driver);

    }



可是看上面的Driver源代码中,有这么一段:
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}


也就是说,在new Driver()的时候,就已经完成了注册,为什么我们还需要使用