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

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

问题描述

我被告知加载JDBC驱动程序的首选方法是:

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

Class.forName(driverName);

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

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 




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

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

在这种情况下,Java开发人员如何仅使用此语句设法促进驱动程序对象的存在?

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

推荐答案

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

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());
    }

}

请注意,存在错误的JDBC驱动程序例如 org.gjt.mm.mysql.Driver 而是错误地在构造函数中注册自己。这就是为什么你需要在这些驱动程序之后调用 newInstance()来让他们自己注册。

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天全站免登陆