Most of the projects require connecting to a database, the basic steps involved in connecting to a database using JDBC are:

  1. Loading the appropriate driver,
  2. Establishing a connection to the database,
  3. Executing the SQL queries using objects of Statement, PreparedStatement, etc., and
  4. Using the ResultSet object and closing the connection.

All these steps excluding the first step appears to have some purpose and can be understood intuitively. Loading of the driver can be explained as the process of loading the driver class into the memory for using its functionality during the execution process.

The different ways by which we can load a JDBC driver are illustrated:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

In the above line, “Class” is a class in java.lang package and we are calling the static method “forName” in that “Class” class. The forName() takes one argument as class name and returns the “Class” object associated with the argument class name so, an object associated with the driver class “sun.jdbc.odbc.JdbcOdbcDriver” is loaded into memory when the above statement is executed.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

The above statement is a bit different from the first one but, it is also used for the same purpose of loading a JDBC driver, except with a minute difference that it calls “newInstance” method of “Class” class which creates a new instance of the class represented by the calling “Class” object. Some programmers use the above statement to load a JDBC driver by specifying the reason that some JVM environments require instantiation of JDBC driver for its proper working, but i haven’t faced any issues when i didn’t used newInstance() method.

new sun.jdbc.odbc.JdbcOdbcDriver();

The above statement creates an object of the JDBC driver, which signifies that the driver is loaded into memory because, whenever an object is instantiated it is loaded into memory.

DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

The above statement not just creates an object of the JDBC driver but also register the driver with the DriverManager. The above statement is useful when dealing with more than one kind of driver classes.
There are many other ways by which we can load a JDBC driver, all these ways eventually would lead to loading of the driver into the memory. Of all these ways, using forName() method is advised because, the JDBC driver class can be changed dynamically.
Apart from all this stuff i would also want to mention that from JDBC 4.0 (included in Java SE 6) does not require loading the driver manually, driver is automatically loaded while the request for database connection is made so, no more worrying about choosing and loading JDBC drivers :) .
If you found this post of some use or, if there are any mistakes and so on, just leave your comments below.

 

Advertisement