1

I've tested that I am able to instantiate jdbc java.mysql.jdbc.Driver using new java.mysql.jdbc.Driver() instead of Class.forName(java.mysql.jdbc.Driver).

Just wanted to know which one is a better way to load the Driver into memory and why ?

Please refer me to some internet links for the same :)

Ankit
  • 609
  • 2
  • 10
  • 26
  • 3
    Driver class has a static block that will execute when class been loaded, So when you say class.forName it will load class in memory if it was not already loaded. But when you use new it will create new object that is really not required. so class.forName approach is better. – Naveen Ramawat Mar 18 '15 at 06:43
  • The main difference is that Class.forName returns a cless object while the constrcutor returns an instance of the mysql driver. Your question is already answered in the accepted answer for question [What is the actual use of Class.forName(“oracle.jdbc.driver.OracleDriver”) while connecting to a DataBase?](http://stackoverflow.com/questions/8053095/what-is-the-actual-use-of-class-fornameoracle-jdbc-driver-oracledriver-while) – akhilless Mar 18 '15 at 06:46

1 Answers1

0

By convention, drivers initialize and register themselves when the class is initialized. The Class.forName() call does exactly that: it loads and initializes the class (without creating an instance)

It also allows the driver to be configurable, since the class name is just a String which you can read from a configuration file.

In "real life" you wouldn't make the Class.forName() call yourself, loading the JDBC driver is usually handled by a persistence framework - which, of course is configurable and get the driver name from some configuration file.

Brett Kail
  • 33,593
  • 2
  • 85
  • 90
Thomas Stets
  • 3,015
  • 4
  • 17
  • 29
  • Configuring the driver class is the most important reason. Applications usually try to be compatible with different databases (with a configuration telling them what driver and server they should use), but even with a fixed DBMS there might be a choice of different drivers, like Oracle Thin vs. Oracle OCI or "real" drivers vs. some proxy driver that calls them. – Lorenzo Gatti Mar 18 '15 at 08:59