Why Use Reflective Loading Database Driver

Keywords: MySQL JDBC Database Java

public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/test";
            String username = "root";
            String password = "root";
            Connection conn = DriverManager.getConnection(url, username, password);
            PreparedStatement stmt = conn.prepareStatement("select name,age from person");
            ResultSet rs = stmt.executeQuery();
            while(rs.next()){
                String name = rs.getString(1);
                Integer age = rs.getInt(2);
                System.out.println(name+"  "+age);
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            System.out.println("Load Driver Failure");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The above is a simple process for native jdbc to load mysql drivers to get connections and execute queries.
Reflection we know is the active use of a class, will trigger the initialization process of the class. In the definition of jvm, there is no specific stipulation on the implementation of the first few steps of class loading, but the initialization process has been specified. Any active use of a class will trigger initialization, since initialization. Triggered, then "load, connect (validate, prepare, parse (not necessarily in this step)", initialization"must be executed.
In addition, the initialization of a class depends first on whether its parent class has been initialized or not, and if not, the initialization of the parent class should be carried out first.
Initialization is to call its static code block and assign values to static variables.
Let's see what com.mysql.jdbc.Driver did during initialization.

static {
        try {
            // Put it in a copy on writearraylist
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

Thus, Driver registers itself in Driver Manger through static code blocks, which is the next step.
Connection conn = DriverManager.getConnection(url, username, password);
To get the reason for the connection, look at the specific code

 for(DriverInfo aDriver : registeredDrivers) {
            // If the caller does not have permission to load the driver then
            // skip it.
            if(isDriverAllowed(aDriver.driver, callerCL)) {
                try {
                    println("    trying " + aDriver.driver.getClass().getName());
                    // Get the connection through the connect method of the specific registered driver
                    Connection con = aDriver.driver.connect(url, info);
                    if (con != null) {
                        // Success!
                        println("getConnection returning " + aDriver.driver.getClass().getName());
                        return (con);
                    }
                } catch (SQLException ex) {
                    if (reason == null) {
                        reason = ex;
                    }
                }

            } else {
                println("    skipping: " + aDriver.getClass().getName());
            }

        }

Essentially, the connection method of mysql.Driver is called to complete the next execution of sql by establishing a socket connection to the database.
JDBC is just a kind of java connection specification proposed by jdk, which provides some interfaces and abstract methods, but does not provide the implementation of a specific database. JDBC is implemented by various database manufacturers, such as mysql.Driver mentioned above.

In fact, as long as the active use of com.mysql.jdbc.Driver triggers that registration operation, why do we have to use reflection? Because reflection is a Class object dynamically generated at runtime based on the full Class name, it can be written in xml or properties. It is not only decoupled from the code, but also does not need to recompile the code when changing the database. This is better than the direct new com.mysql.jdbc.Driver. Yes.~

Posted by Deadmeat on Thu, 11 Jul 2019 16:16:41 -0700