加载 JDBC 驱动程序 [英] Loading JDBC driver

查看:46
本文介绍了加载 JDBC 驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说加载 JDBC 驱动程序的首选方法是:

Class.forName(driverName);

我知道这对于从 XML 配置文件或用户输入读取的多个驱动程序之间的动态决策更好.我很好奇的是如何调用此语句将声明的驱动程序加载到我们甚至不在任何地方存储结果类"对象的环境中.JavaDocs 条目说:

public static Class forName(String className)抛出 ClassNotFoundExceptionReturns

<块引用>

返回与给定字符串名称的类或接口关联的类对象

在这种情况下,Java 开发人员如何仅通过此语句就能够促进驱动程序对象的存在?

解决方案

Class#forName() 运行 静态初始化器(你知道,static 适用于类,而不适用于实例).JDBC 驱动程序实现应该在静态初始化器.

public class SomeDriver 实现 Driver {静止的 {DriverManager.registerDriver(new SomeDriver());}}

请注意,存在有缺陷的 JDBC 驱动程序,例如 org.gjt.mm.mysql.Driver,它错误地在构造函数中注册了自身.这就是为什么您之后需要对此类驱动程序进行 newInstance() 调用以让它们自行注册的原因.

I am told that the prefered method to load the JDBC driver is :

Class.forName(driverName);

I understand that this is better for a dynamic decision between multiple drivers maybe read from an XML config file or user input. The thing I am curious about is how does invoking this statement loads the stated driver into the environment where we are not even storing the resultant "Class" object anywhere. The JavaDocs entry says:

public static Class forName(String className)
                 throws ClassNotFoundExceptionReturns 

returns the Class object associated with the class or interface with the given string name

In that case, how do the Java developers managed to facilitate the existence of driver object with merely this statement?

解决方案

The Class#forName() runs the static initializers (you know, static applies to the class, not to the instance). The JDBC driver implementation should register itself in the static initializer.

public class SomeDriver implements Driver {

    static {
        DriverManager.registerDriver(new SomeDriver());
    }

}

Note that there exist buggy JDBC drivers such as org.gjt.mm.mysql.Driver which incorrectly registers itself inside the constructor instead. That's why you need a newInstance() call afterwards on such drivers to get them to register themselves.

这篇关于加载 JDBC 驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆