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....");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With