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!

- 4,824
- 13
- 51
- 88
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.

- 127,052
- 24
- 157
- 134
-
thanks! one last qn- if u do instantiate it, then the subsequent DriverManager.getConnection(..) will not re-instantiate it again, correct? It will do so only if you didnt instantiate it in the first step? – OckhamsRazor Jan 09 '11 at 16:37
-
I suspect that just by loading the class, the driver manager has already instantiated it, triggered by a static block in the driver. To be honest, I'm not entirely sure. If you want to use the driver you have instantiated (e.g. to wrap around it), you need to either avoid using DriverManager to get connections, or register your own driver instance using the DriverManager static methods. – araqnid Jan 09 '11 at 16:41
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.

- 93
- 8