Why do we use Class.forName to register Drivers


This code is forcing the class representing the MySQL driver to load and initialize. In Java, a class is not loaded unless it is necessary that the class gets loaded. Since JDBC code usually never directly references the driver, it wouldn’t get loaded without Class.forName (or some other equivalent alternatives).

Note that it is necessary to both load and initialize the class, which are 2 different things.

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

Also, note that it is not necessary to call .newInstance() — the static initializer of the Driver already registers itself as a JDBC driver.

Finally, note that with the Service Loader API it is usually not necessary to call Class.forName() to load the driver: it can be loaded automatically.

 

 

Thank you for Reading

About pacesettergraam

A good and realistic person

Posted on August 22, 2013, in Java. Bookmark the permalink. 2 Comments.

  1. Hi there,
    I totally appreciate your new page on Why do we use Class.forName to register Drivers | pacesettergraam and and look forward to more!
    Bye for now!!

  2. Hi.
    Through this posting you express quite a few of the more significant pieces of information!!
    Fairly simple to read through & including interesting detail!
    Thanks a lot for posting Why do we use Class.forName to register Drivers | pacesettergraam!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: