Why does calling Class.forName(“com.mysql.jdbc.Dri

2019-05-15 22:11发布

问题:

This question already has an answer here:

  • JDBC Class.forName vs DriverManager.registerDriver 3 answers

As explained in What is the difference between "Class.forName()" and "Class.forName().newInstance()"?, the method Class.forName() does the following:

Calling Class.forName(String) returns the Class object associated with the class or interface with the given string name

But, if it only does that, why is it then neccesary to call this method in order to use MySQL with Java? Without it I get the following error:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/calender
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at Database.main(Database.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

回答1:

It registers it because it loads the class into memory and runs the class's static initializers. The static initializer code then calls into the JDBC framework to say "Hi there, I'm a JDBC driver" (by calling DriverManager.registerDriver).

E.g., the driver class will look vaguely like this:

package com.example.jdbc;

import java.sql.DriverManager;

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

    // ...implementation...
}

Then when you do Class.forName("com.example.jdbc.Driver"), it loads the class and runs the static initializer, which creates an instance and registers it with the DriverManager.


I should note that as Andreas says, modern JDBC drivers don't need you to do this.



标签: java mysql jdbc