Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC connection- Class.forName vs Class.forName().newInstance?

Tags:

mysql

jdbc

Was wondering why both Class.forName("com.mysql.jdbc.Driver"); and Class.forName("com.mysql.jdbc.Driver").newInstance(); work when i use them to connect to a database. By right, isn't the former not supposed to work, since no new instance was created. And yet, it still works. Im using netbeans 6.9.1. Thanks for your input!

like image 519
OckhamsRazor Avatar asked Jan 09 '11 16:01

OckhamsRazor


2 Answers

Class.forName("xxx") doesn't create a connection to the database, it just loads the JDBC driver and registers it so that a subsequent DriverManager.getConnection(...) call will work. Instantiating the driver yourself is not necessary.

like image 110
araqnid Avatar answered Sep 22 '22 19:09

araqnid


With a driver which supports jdbc 4.0 you don't even need Class.forName(). The driver is supposed to have in built mechanism to load itself on the fly, when DriverManager looks up for it.

(ref: http://download.oracle.com/javase/6/docs/api/java/sql/DriverManager.html) The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

my.sql.Driver

Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

like image 20
voiddrum Avatar answered Sep 23 '22 19:09

voiddrum