Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Class.forName() method does for JDBC? [duplicate]

Tags:

java

jdbc

I have found that Class.forName method initializes static blocks.

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

After jdbc 4.0 you don't need to call this method. But people always use this method even after jdbc 4.0 version. My question is why do I need to use this method if I use jdbc 4.0? What Class.forName() method does for JDBC 4.0 and after?

Here is my example code. I only add mysql-connector.jar to my library and When I run this code It works perfectly.

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
like image 948
hellzone Avatar asked Mar 10 '23 22:03

hellzone


2 Answers

It gets the Class object represented by the given FQN. If not loaded previously, it also loads the class. This has the side effect of initializing the static class variables and running any static blocks.

With recent JDBC versions you don't need Class.forName() to load the driver anymore, with older driver versions it was and is required.

like image 112
Kayaman Avatar answered Mar 19 '23 08:03

Kayaman


It is, on up to date runtimes, pretty pointless except for one thing: if the (correct) driver jar is missing on the runtime classpath this line of code will tell you exactly that.

Should that line of code be removed, you will get a generic failure when the code attempts to create a connection; a failure which has several sources including another very common mistake, which is to use the wrong JDBC connection url. It muddies the water trying to troubleshoot problems.

like image 24
Gimby Avatar answered Mar 19 '23 08:03

Gimby