Skip to main content

class.forName(String className) used in JDBC unfolded

During many interviews I have taken , I have observed even seasoned programmers find it difficult to explain the use of class.forname() method while making a JDBC connection object. In this post, I am just trying to explain this,
Here is a simple JDBC code,



import java.sql.*;
public class JdbcConCode {
public static void main(String args[]) {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/nilesh";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "nilesh";
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
System.out.println("Connection is created....");
//TODO
//rest of the code goes here
} catch (Exception e) {
System.out.println(e);
}
}
}

Let's go through the code above, the url indicates the location of the database schema, here the database is nilesh.
Then there is Driver which is the fully qualified JDBC driver class name.
Other two variables are used to declare the username and passwords to access the database. Just for the purpose of this code and to maintain simplicity ,I have mentioned all these variables inside the class itself, generally, this kind of details are retrived through the properties or xml files.Let's not delve into those details, the actual code starts after the try{ block,
class.forName(String className)

Basically, here the forName() call tries to locate, load and link the driver class to JDBC API. With in java , dynamic loading is acheived by class.forName() and it is the basis of core reflection functionality provided by Java.
Class.forName attempts to load the class whose name is
given in its only argument (driver class), and returns the Class instance representing that class. In the
event that the Class could not be found, resolved, verified, or loaded, Class.forName
throws one of several different Exceptions, all of which are listed in the javadoc page for
java.lang.Class [1].
Back to the code, here the class.forName() is called as,
class.forName("com.mysql.jdbc.Driver");

Using the complete package name , it first locates the class binary in the classpath and then loads that as a object representation in memory.
Once the Driver class is loaded in memory , it's static code block is executed which has something like,

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

That is the Driver gets registered with JDBC api as soon as class.forName() executes. So it calls a static method in the java.sql.DriverManager class which apparently registers a copy of itself when it loads.

Since the Driver is registered the next line of code just get us the Connection() class object to work with database. But thats not that straight forward.
We all know that the DriverManager class returns a database connection given a JDBC URL string, a username and a password. However, in order to create that connection, the
DriverManager
class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that are registered with it (ie: the registerDriver(Driver driver) method ) and calls the acceptsURL(url)) method on each driver in the array, effectively asking the driver to tell it whether or not it is compatible to handle the JDBC calls.
So this explains how the class.forName() works for you.

Comments

  1. Jumanji Slot Review - Jumanji Online Slot Review - JTM Hub
    Play 여주 출장샵 the 서울특별 출장안마 Jumanji online 양산 출장마사지 slot at Jumanji.com - a brand new online 삼척 출장마사지 casino with great bonuses 창원 출장마사지 and promotions!

    ReplyDelete

Post a Comment

Popular posts from this blog

Exporting/Saving Putty/SecureCRT/SecureFX sessions on Windows!!

This is my first stint with blogging and I thought why not just start with sharing some useful information/tricks  that can save you some time. To begin with , here are couple of tips that could save you some time. Actually, I had once this problem where I have to take backup and move my work data to a new laptop and as we normally do , I also put my data on some external drive and copied it to the new box. During all this exercise I realized that by this I can only back up the data, what about the work I am doing..my configurations and installations...? What the heck...I need to spend lot of time to redo all that...crap. I was using Putty, SecureCRT and SecureFX to log on to client side boxes and to work upon. And all three had at least 30 saved sessions having IP/user/pwd information, reconfiguring those sessions would be a daunting tasks. I did some research "well by that I meant googling also..:)" and here is how a little information can help you.. If you are usin

What is big data ? and what role Hadoop has to play?

In recent times we have been hearing , reading (in many blogs) quite often about cloud computing ,big data and HPC ie. high performance computing. Undoubtedly, these are the buzz words for this decade. If you have been in the industry for quite some time then you can recall last decade was web 2.0 decade. So what is big data? Is it a new framework or new data modelling technique or part of NO SQL movement? I have seen many times people relate big data to one of these or they are confused about it. Same is with HADOOP, it is thought as a NO SQL database framework. Big data is nothing but just huge amount of data which requires mining. Per wiki , Big Data is a term applied to data sets whose size is beyond the ability of commonly used software tools to capture, manage, and process the data within a tolerable elapsed time. Big data sizes are a constantly moving target currently ranging from a few dozen terabytes to many petabytes of data in a single data set.So big data is a hovering p