加载 JDBC 驱动程序

发布于 2024-11-07 01:22:56 字数 439 浏览 0 评论 0原文

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

Class.forName(driverName);

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

public static Class forName(String className)
                 throws ClassNotFoundExceptionReturns 

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魂归处 2024-11-14 01:22:56

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

public class SomeDriver implements Driver {

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

}

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文