gpt4 book ai didi

java - 为什么是 Class.forName ('database driver' )?

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:12 25 4
gpt4 key购买 nike

为什么

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
dbConnection = DriverManager.getConnection(strUrl, props);

代替

dbConnection = EmbeddedDriver.connect(strUrl, props);

?

指定字符串而不是编译器可以检查的类名不是更容易出错吗?我看到一个示例,其中类名是从配置中获取的,但这似乎是无论可用替代方案如何都使用的模式。

最佳答案

使用 JDBC 4.0 驱动程序(及更高版本),您只需要

dbConnection = DriverManager.getConnection(strUrl, props);

根据 DriverManager java文档,

JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

my.sql.Driver

Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

关于java - 为什么是 Class.forName ('database driver' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24657266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com