Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading JDBC driver

Tags:

java

jdbc

I am told that the prefered method to load the JDBC driver is :

Class.forName(driverName);

I understand that this is better for a dynamic decision between multiple drivers maybe read from an XML config file or user input. The thing I am curious about is how does invoking this statement loads the stated driver into the environment where we are not even storing the resultant "Class" object anywhere. The JavaDocs entry says:

public static Class forName(String className)
                 throws ClassNotFoundExceptionReturns 

returns the Class object associated with the class or interface with the given string name

In that case, how do the Java developers managed to facilitate the existence of driver object with merely this statement?

like image 305
mihsathe Avatar asked May 13 '11 12:05

mihsathe


People also ask

What is the right syntax to load JDBC driver?

Class class to load the JDBC drivers directly. For example: Class. forName ("oracle. jdbc.

Why do we load drivers in Java?

You must register the driver in your program before you use it. Registering the driver is the process by which the Oracle driver's class file is loaded into the memory, so it can be utilized as an implementation of the JDBC interfaces.

What Is syntax of loading DriverManager?

Driver is loaded with the following statement: Class. forName("my. sql. Driver"); When getConnection is called the DriverManager 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 Answers

The Class#forName() runs the static initializers (you know, static applies to the class, not to the instance). The JDBC driver implementation should register itself in the static initializer.

public class SomeDriver implements Driver {

    static {
        DriverManager.registerDriver(new SomeDriver());
    }

}

Note that there exist buggy JDBC drivers such as org.gjt.mm.mysql.Driver which incorrectly registers itself inside the constructor instead. That's why you need a newInstance() call afterwards on such drivers to get them to register themselves.

like image 127
BalusC Avatar answered Oct 14 '22 19:10

BalusC