MySQL驱动类加载

这是一篇两年前的存稿,时间太快,都来不及写一小篇文字,不知十年后回想起这段时光,是悔不当初还是别的感触?

分析这句话的原理

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

普通写法

Class.forName("com.mysql.jdbc.Driver");   
String url = "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";   
String user = "";   
String psw = "";   
Connection con = DriverManager.getConnection(url,user,psw);  

可以替换成以下语句

com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();   
//or:   
//new com.mysql.jdbc.Driver();   
String url = "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";   
String user = "";   
String psw = "";   
Connection con = DriverManager.getConnection(url,user,psw);

以下代码是错误示范,这样写仅仅使Dirver类被装载到jvm中,却未进行相应的初始化工作 ???

com.mysql.jdbc.Driver driver = null;   
//or:   
ClassLoader cl = new ClassLoader();   
cl.loadClass("com.mysql.jdbc.Driver");  

JDBC 是使用 Bridge 模式进行设计的,When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager

package com.mysql.jdbc   
  
public class Driver extends NonRegisteringDriver implements java.sql.Driver {   
 // ~ Static fields/initializers   
 // --------------------------------------------- //   
 // Register ourselves with the DriverManager   
 //   
 static {   
    t ry {   
              java.sql.DriverManager.registerDriver(new Driver());   
          } catch (SQLException E) {   
              throw new RuntimeException("Can't register driver!");   
          }   
  }   
// ~ Constructors   
 // -----------------------------------------------------------   
/**  
  * Construct a new driver and register it with DriverManager  
  *   
  * @throws SQLException  
  *             if a database error occurs.  
  */  
 public Driver() throws SQLException {   
     // Required for Class.forName().newInstance()   
 }   
}  

by 费城的二鹏 2018.12.20 长春

你可能感兴趣的:(MySQL驱动类加载)