好神奇的JDBC连接

JDBC连接步骤:
1.加载驱动
2.获得连接
3.创建Statement对象
4.执行SQL
5.关闭连接

以上5步没问题吧?可不可以简化?

在我印象里自己写JDBC时,一直都是以上五步的,可是今天彻底的给我改变了

首先代码如下:

// 加载驱动
public DBUtils() {
try {
Class.forName(driverName);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

// 建立连接
public synchronized Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = java.sql.DriverManager.getConnection(dbURL, userName, userPwd);
}
return conn;
}
……
但是我在调用时,报错 ClassNotFount:com.mysql.jdc.Driver
这个错误报的没问题,因为驱动类路径写错了,但是神奇的是,竟然SQL还执行了并返回了查询结果。
因此我试着不写第一步代码如下:
// 加载驱动
public DBUtils() {
// try {
// Class.forName(driverName);
// } catch (Exception e) {
// System.out.println(e.getMessage());
// }
}

// 建立连接
public synchronized Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = java.sql.DriverManager.getConnection(dbURL, userName, userPwd);
}
return conn;
}
……
然后执行查询语句,也执行成功并返回了查询结果。

因此我产生了一个问题:Class.forName(driverName)这句话的作用是什么,有什么意义?实验证明我们可以不需要加载驱动的。

1、Class.forName(驱动) 是加载类 并执行static初始化,如mysql驱动实现:
[code="java"]static
{
try
{
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
[/code]

自动调用DriverManager.registerDriver(new Driver()); 注册驱动;

2、DriverManager.getConnection(url, username, password)获取连接时,会根据url获取驱动信息:
[code="java"] public static Driver getDriver(String url)
throws SQLException {
java.util.Vector drivers = null;

    println("DriverManager.getDriver(\"" + url + "\")");

    if (!initialized) {
        initialize();
    }

synchronized (DriverManager.class){ 
        // use the read copy of the drivers vector
    drivers = readDrivers;  
    }

    // Gets the classloader of the code that called this method, may 
// be null.
ClassLoader callerCL = DriverManager.getCallerClassLoader();

    // Walk through the loaded drivers attempting to locate someone
// who understands the given URL.
    for (int i = 0; i < drivers.size(); i++) {
        DriverInfo di = (DriverInfo)drivers.elementAt(i);
    // If the caller does not have permission to load the driver then 
    // skip it.
        if ( getCallerClass(callerCL, di.driverClassName ) != 
     di.driverClass ) {
            println("    skipping: " + di);
            continue;
        }
        try {
            println("    trying " + di);
    if (di.driver.acceptsURL(url)) {
        // Success!
                println("getDriver returning " + di);
                return (di.driver);
            }
        } catch (SQLException ex) {
    // Drop through and try the next driver.
        }
    }

    println("getDriver: no suitable driver");
    throw new SQLException("No suitable driver", "08001");
}

[/code]
2.1、drivers 就是我们注册的驱动集合;
2.2、if (di.driver.acceptsURL(url)) 判断驱动是否接受我们的url;

3、你必须注册驱动,不管通过Class.forName 还是DriverManager.registerDriver。

4、你可以在sql执行之前 通过DriverManager.getDrivers() 看看是否已经注册了驱动。

Class.forName(driverName); 就是把驱动类加载到jvm中,现在已经可以获取connection并且能执行,这说明你的运行环境中,执行你这段代码钱jdbc 的driver已经加载到了jvm中。

forName(String className) api中的解释:返回与带有给定字符串名的类或接口相关联的 Class 对象
意思就是根据类的包和名称在jvm中创建一个对象实例,并且返回。对于jdbc Class.forName(driverName); 意思就是把驱动类加载到jvm中

这个一点都不神奇,Class.forName(driverName)也就是创建一个类实例,和可以理解为new一个class。 你去掉了Class.forName(driverName)会成功是因为你在第一次运行的时候没有删除,在jvm里面已经创建了数据库的驱动对象类,所以去掉了后也能返回结果。如果重启jvm不加那句肯定会出错,简单点你可以关掉eclipse在打开 运行。