Class.forName("org.gjt.mm.mysql.Driver");注册驱动
学校时,照抄老师的代码。工作时,直接调用成熟框架的方法。从没有真正自己研究下。(惭愧)
今天试着自己写写JDBC连接数据库。
看到代码
……
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection(url,username,password);
……
我在想孤零零的一句【Class.forName("org.gjt.mm.mysql.Driver");】到底做了什么,网友说:注册MySql驱动。可是自己习惯思维是,看到调用。这连引用都没有。它加载了谁,又调用了谁呢?
想不出来!“何不看看驱动源码”呢?对啊!理解解压【org.gjt.mm.mysql.Driver】
org\gjt\mm\mysql文件夹下就一个文件:类Driver
- package org.gjt.mm.mysql;
- import java.sql.SQLException;
- public class Driver extends com.mysql.jdbc.Driver
- {
- }
package org.gjt.mm.mysql; import java.sql.SQLException; public class Driver extends com.mysql.jdbc.Driver { }
再去看看 com.mysql.jdbc.Driver
- package com.mysql.jdbc;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- public class Driver extends NonRegisteringDriver
- implements java.sql.Driver
- {
- static
- {
- try
- {
- DriverManager.registerDriver(new Driver());
- } catch (SQLException E) {
- throw new RuntimeException("Can't register driver!");
- }
- }
- }
package com.mysql.jdbc; import java.sql.DriverManager; import java.sql.SQLException; public class Driver extends NonRegisteringDriver implements java.sql.Driver { static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } }
兜兜转转,最后调用的还是【DriverManager.registerDriver(new Driver());】
但源文件里的
- public static synchronized void registerDriver(java.sql.Driver driver)
- throws SQLException {
- if (!initialized) {
- initialize();
- }
- DriverInfo di = new DriverInfo();
- di.driver = driver;
- di.driverClass = driver.getClass();
- di.driverClassName = di.driverClass.getName();
- // Not Required -- drivers.addElement(di);
- writeDrivers.addElement(di);
- println("registerDriver: " + di);
- /* update the read copy of drivers vector */
- readDrivers = (java.util.Vector) writeDrivers.clone();
- }