Why JDBC calls Class.forName (go) before getconnection

Source: Internet
Author: User
Tags driver manager

The generic template for getting a database connection is as follows:

String driver = "oracle.jdbc.OracleDriver";String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";String user = "scott";String password = "ticmy";Class.forName(driver);Connection conn = DriverManager.getConnection(url, user, password);

There is a class.forname (driver), what is the function of this sentence? Load the driver class into memory? What if there's no such thing? Running the discovery, if you remove this sentence will have the following exception:
Java.sql.SQLException:No suitable driver found for xxx ....

Just look at what Class.forName did before explaining the specific reason.

Assuming that a class has never been loaded into memory before, Class.forName (String className) does the following things:
1, loading. Reads the bytecode into memory and produces a corresponding Java.lang.Class class object
2, connection. This step validates the bytecode, allocates memory for the static variable, assigns the default value (0 or null), and optionally resolves the symbol reference (it doesn't matter here)
3, initialization. assign an initial value to the static variable of the class , if there is a static int a = 1; The operation that assigns a value of 1 is this time. In addition to this, the static block of the class is called . (This step is the main point)

The Class.forName (String className) method will do all three steps, as in the following example:

package com.ticmy.oracle;public class TestClinit {    public static void main(String[] args) throws Exception {        Class.forName("com.ticmy.oracle.ABC");    }}class ABC {    private static int a = getNum();    static {        System.out.println("this is static block");    }    public static int getNum() {        System.out.println("getNum");        return 1;    }}

The running result of the program is:
Getnum
This is static block

So, is there any static block in the driver class of Class.forName (driver)? to explore. The example is Oracle, Anti-compilation under Oracle.jdbc.OracleDriver, found that it inherits the Oracle.jdbc.driver.OracleDriver, then continue to see this oracle.jdbc.driver.OracleDriver, there is a static block, there is Such a code:

static {    Timestamp localTimestamp = Timestamp.valueOf("2000-01-01 00:00:00.0");    try {      if (defaultDriver == null) {        defaultDriver = new OracleDriver();        DriverManager.registerDriver(defaultDriver);      }    } catch (RuntimeException localRuntimeException) {    } catch (SQLException localSQLException){}    _Copyright_2004_Oracle_All_Rights_Reserved_ = null;}

Look at MySQL again: com.mysql.jdbc.Driver:
Also found the static block, the code is as follows:

static {    try {      DriverManager.registerDriver(new Driver());    } catch (SQLException E) {      throw new RuntimeException("Can‘t register driver!");    }}

Look at one more db2:com.ibm.db2.jcc.DB2Driver:
A static block was also found:

static {    if (o.Nb != null) {      exceptionsOnLoadDriver__ = dg.a(o.Nb, exceptionsOnLoadDriver__);    }    try {      registeredDriver__ = new DB2Driver();      DriverManager.registerDriver(registeredDriver__);    }    catch (SQLException localSQLException) {      exceptionsOnLoadDriver__ = new SqlException(null,       "Error occurred while trying to register Jcc driver with JDBC 1 Driver Manager");      exceptionsOnLoadDriver__.setNextException(localSQLException);    }}

There are no exceptions to the discovery that there are drivermanager.registerdriver (driver) calls. So is it possible to replace the class.forname in the first example with the Drivermanager.registerdriver?

String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";String user = "scott";String password = "ticmy";DriverManager.registerDriver(newOracleDriver());Connection conn = DriverManager.getConnection(url, user, password);System.out.println(conn);conn.close();

Tested found OK. Now, you know that the fundamental purpose of class.forname (driver) is to invoke Drivermanager.registerdriver.

Class.forName also has an overloaded method: Class.forName (String name, Boolean initialize, ClassLoader loader), Class.forName (string ClassName) is equivalent to Class.forName (ClassName, True, Currentloader), note that the middle parameter is true, and the meaning of this parameter is to not initialize. If this parameter is true and the specified class has not been initialized before, it is initialized.

In addition, JDBC4 has no need to explicitly call Class.forName, in JDBC4, call Getconnection when DriverManager will automatically load the appropriate driver.
http://www.ticmy.com/?p=249

Why JDBC calls Class.forName (go) before getconnection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.