面试被问:JDBC底层是如何连接数据库的?( 二 )


 
Driver接口java.sql.Driver此接口是提供给数据库厂商实现的 。比如说MySQL的,需要依赖对应的jar包 。
<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>8.0.16</version></dependency>MySQL数据库对应的实现驱动实现类:
package com.mysql.cj.jdbc;import java.sql.SQLException; public class Driver extends NonRegisteringDriver implements java.sql.Driver {    static {        try {            //注册驱动            java.sql.DriverManager.registerDriver(new Driver());        } catch (SQLException E) {            throw new RuntimeException("Can't register driver!");        }    }     public Driver() throws SQLException {     }}DriverManager是rt.jar包下的类,(rt=runtime),把我们需要驱动类注册进去 。
//DriverManager类中的方法public static synchronized void registerDriver(java.sql.Driver driver, DriverAction da)    throws SQLException {     /* Register the driver if it has not already been added to our list */     if(driver != null) {          registeredDrivers.addIfAbsent(new DriverInfo(driver, da));      } else {          // This is for compatibility with the original DriverManager          throw new NullPointerException();      }      println("registerDriver: " + driver);}相应装载Oracle驱动:
Class.forName("oracle.jdbc.driver.OracleDriver"); Sql Server驱动:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");获取链接给我们看起来就这一行代码:
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);下面我们进行深入聊聊这行代码,到底底层是怎么连接数据库的?
getConnection方法三个参数:链接地址,用户名和密码 。
public static Connection getConnection(String url,     String user, String password) throws SQLException {     java.util.Properties info = new java.util.Properties();     if (user != null) {         info.put("user", user);     }     if (password != null) {         info.put("password", password);     }   return (getConnection(url, info, Reflection.getCallerClass())); }创建一个Properties对象,Properties是HashTable的子类 。
public class Properties extends Hashtable<Object,Object> {    //.....}再看getConnection方法:
//  Worker method called by the public getConnection() methods.private static Connection getConnection(        String url, java.util.Properties info, Class<?> caller) throws SQLException {  ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;  SQLException reason = null;  //遍历气门注册的数据库驱动  for(DriverInfo aDriver : registeredDrivers) {             try {                 //获取连接                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;                 }            }      }}


推荐阅读