sagar
sagar

Reputation: 745

Why cant we statically load the sql Driver class in connecting to mysql through jdbc?

I know that in order to connect java code to mysql we have to load com.mysql.jdbc.Driver by any one of the folllowing options we have(i am not sure about all of them) :-

Class.forName("com.mysql.jdbc.Driver");
OR
Class.forName("com.mysql.jdbc.Driver").newInstance();
OR
System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
OR 
//through command prompt
java -Djdbc.drivers=com.mysql.jdbc.Driver ProgramName
Or
DriverManager.registerDriver("com.mysql.jdbc.Driver");

My Questions :-

First Question- I want to confirm that are all of the above methods legal to load the driver class.

Second Question:- The second method that we have, i.e.

Class.forName("com.mysql.jdbc.Driver").newInstance();

is same as doing object creation by using new keyword. For eg.

new com.mysql.jdbc.Driver();

I have tried through this and it works. So, why can't we use the second approach? Is there any disadvantage of using it.?

I think i have made my both questions clear , if not, please comment, i will edit it.

Upvotes: 0

Views: 976

Answers (1)

M. Deinum
M. Deinum

Reputation: 124899

As of JDBC 4.0 and the Service Provider API in Java you as a developer shouldn't load the drivers anymore. Any JDBC 4 capable driver should provide a file containing the actual driver class to load. The java.sql.DriverManager will use the Service Provider to load all available Driver classes in the classpath.

So although all the ways you showed are valid you shouldn't use them anymore. I would consider tutorials that still use that way of loading drivers obsolete. Even H2 and Derby provide this mechanism (at least MySQL, Oracle and Microsoft also support this also). So the only thing, when using a DriverManager you should do in your code is

DriverManager.getConnection("jdbc:mysql://localhost/yourdb");

To answer your second question the difference between Class.forName("com.mysql.jdbc.Driver").newInstance(); and new com.mysql.jdbc.Driver(); is a bit more difficult as you get into static linking and classloading. In the end you end-up with the same result an instance of the com.mysql.jdbc.Driver.

However the new com.mysql.jdbc.Driver(); will lead to a static link to this class as it will be part of your classes import statements. So as soon as you load this class and the com.mysql.jdbc.Driver class isn't available it will crash.

Whereas the Class.forName("com.mysql.jdbc.Driver").newInstance(); will at runtime try to load the class. It will also fail with a classnotfound but you could catch it and try to load another driver or show a nice message to the user.

But as mentioned you shouldn't be doing either of those and let the JDBC drivers auto-load.

Upvotes: 3

Related Questions