what exactly does this do Class.forName("com.mysql.jdbc.Driver").newInstance();
Asked Answered
S

5

23

While connecting to MySQL database I do following steps

Connection con = null;
Resultset rs = null;
Statement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","passwp");

Actually I wanted to know what does Class.forName("com.mysql.jdbc.Driver").newInstance(); statement do.

Althogh this class is not in mysql.jar. Where is it present?

Sharie answered 23/2, 2013 at 10:1 Comment(1)
Note that the code in the question is flawed: people should not copy it.Dvorak
L
24

Note that this answer is addresses the syntactical nature of the question, not the logical aspect. If you want a better understanding of why you would do this, see Koray Tugay's answer.

Also note that as of Java 6, this is no longer required to initialise JDBC 4.0 drivers - instead they are automatically loaded using the service provider pattern at JVM startup.


The Class class is located in the java.lang package, so it is distributed with java, and imported automatically into every class.

What the forName() method does, is just return the Class object for the parameter that was loaded by the class loader. The newInstance() method then returns a new instance of the class.

So then what happens is when you call Class.forName(...) it returns com.mysql.jdbc.Driver.class. You then call newInstance() on that class which returns an instance of the class, with no parameters, so it's basically calling new com.mysql.jdbc.Driver();.

Laurelaureano answered 23/2, 2013 at 10:10 Comment(3)
No problem, the Class/class stuff can be a bit hard to wrap your head around. :)Laurelaureano
I downvoted because either though this is technically correct, it does not help in anyway in understanding why this code is used in this the context of using jdbc connections. It also fails to mention this line of code is no longer necessary. The answer of Koray makes more sense and is more up to date.Tlaxcala
It also fails to note that that classname is deprecated for Connector/J 8.0 and later drivers (though it still currently works).Dvorak
L
13

Quoting from the JDBC Specification, Chapter 9, Section 2:

JDBC drivers must implement the Driver interface, and the implementation must contain a static initializer that will be called when the driver is loaded. This initializer registers a new instance of itself with the DriverManager.

And an example code is provided for AcmeJdbcDriver as follows:

public class AcmeJdbcDriver implements java.sql.Driver {
    static {
        java.sql.DriverManager.registerDriver(newAcmeJdbcDriver());
    }
}

And when you call Class.forName(String className), according to the API Documentation, the following happens:

A call to forName("X") causes the class named X to be initialized.

where initialization involves code in static block to be executed.

So basically, you initialize the Driver class, and in turn the class registers itself with the java.sql.DriverManager per the JDBC specification.

Please note, this is not needed anymore. Details can be found here.

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().

Likable answered 21/5, 2017 at 6:8 Comment(2)
This is a much better explanation! Thank You!Timon
upped for being the only one who mentions that apps don't need to call Class.forName(..) anymoreTonytonya
C
6

It initialize the class "com.mysql.jdbc.Driver" if found in the classpath, this imply that the driver is registered in the JDBC driver manager since the registration process is inside the static initializer of the driver class ...

There is another approach you can use to register a driver : is to use the static DriverManager.registerDriver() method.

Cusec answered 23/2, 2013 at 10:6 Comment(6)
what does the forName method do?Sharie
A call to forName("com.mysql.jdbc.Driver") causes the class named Driver to be initialized.Cusec
i have another question,actually i have forgotten my mysql password and i have checked all the answer in SO about changing mysql password but i could not retrieve it. Can you please help me in thisSharie
@javaL take a look here : dev.mysql.com/doc/refman/5.0/en/resetting-permissions.htmlCusec
you said to use DriverManager.registerDriver.Can you please post the full codeSharie
@javaL I said that you can even use DriverManager.registerDriver but there is nothing against using Class.forNAme ...Cusec
V
5

It will create a new instance of the com.mysql.jdbc.Driver class and hence call the static initialization which will register the driver with the DriverManager so you can create mysql connections based on the URL you use in the second line.

The class however should be in the mysql.jar.

Vespine answered 23/2, 2013 at 10:6 Comment(1)
You do not need to create an instance to run the static block.Likable
D
2

As noted, the code in the question is flawed. These are the things that are wrong with it.

Major:

  • You don't need to call Class.forName to load or initialize a JDBC driver. The DriverManager.getConnection(...) call will do all of that automatically. The Class.forName stuff has been redundant since JDBC 4.0 / Java 6.

    DriverManager.getConnection(...) will select a JDBC driver based on the JDBC URL prefix. It knows how to search the classpath for suitable drivers, load the driver class and trigger initialization to cause it to register.

  • You don't need to call newInstance() to trigger class initialization. In fact, all you are doing is creating an unnecessary instance of the Driver class. And (I think) adding extra checked exceptions that need to be handled.

  • That class name for the JDBC driver is deprecated. As of MySQL Connector/J 8.0 and 8.1, the class name is com.mysql.cj.jdbc.Driver. (The old com.mysql.jdbc.Driver class name still works, but it gives you a runtime warning.)

    Once again DriverManager takes care of this. You don't need to know the driver class name.

Minor:

  • There are some checked exceptions thrown by forName and newInstance that ought to be handled.

  • Wiring your account name and password into your code is a bad idea. Even if you don't intend to publish your code.

Most of these problems are best solved by deleting this line:

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

i.e. the very line that the OP is asking about!

Dvorak answered 17/11, 2023 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.