4

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....");
P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66
hellzone
  • 5,393
  • 25
  • 82
  • 148
  • 4
    Just people copy-pasting code. If you think you don't need it, try your code without it. – OneCricketeer Feb 09 '17 at 08:37
  • 2
    Just as it says, "you don't need to do it in jdbc 4.0". This means that it does nothing extra, and you don't need to call that. Why people still do it? Force of habit, ignorance, "for safety" (in the off-chance of that code being deployed with jdbc pre-4.0). You can choose any of the above, each will apply to someone. – M. Prokhorov Feb 09 '17 at 08:38
  • If the driver jar is not on the system classpath, but only on the context classpath (eg the driver.jar is part of a webapplication WAR), then it may still be necessary to use `Class.forName` to load the driver. – Mark Rotteveel Feb 09 '17 at 09:32

3 Answers3

4

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

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.

Gimby
  • 5,095
  • 2
  • 35
  • 47
1

The question is: How do i know everyone is using jdbc 4.0, and you don't know that. You add this for the people that are testing on older or outdated equipment.

JordanH
  • 190
  • 5
  • You don't know if anyone uses older version. However, always adding a bunch of defensive measures is not going to go you any good. If someone is running old version, let them deal with this themselves. They always know more about their running environment than you do anyway, you can't possibly account for every library combination out there. – M. Prokhorov Feb 09 '17 at 08:50