为什么要使用Class.forName('database driver')? [英] Why Class.forName('database driver')?
问题描述
为什么
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
dbConnection = DriverManager.getConnection(strUrl, props);
代替
dbConnection = EmbeddedDriver.connect(strUrl, props);
?
指定字符串而不是可以由编译器检查的类名是否更容易出错?我看到了一个从配置中获取类名的示例,但这似乎是无论可用替代方法如何都使用的模式.
Isn't it more error-prone to specify a string, instead of a class name that can be checked by the compiler? I saw an example where the class name was obtained from configuration, but this seems to be the pattern that is used regardless of available alternatives.
推荐答案
有了JDBC 4.0驱动程序(及更高版本),您只需
With a JDBC 4.0 driver (and up), all you need is
dbConnection = DriverManager.getConnection(strUrl, props);
根据 DriverManager
javadoc
per the DriverManager
javadoc,
JDBC 4.0驱动程序必须包含文件META-INF/services/java.sql.Driver.该文件包含java.sql.Driver的JDBC驱动程序实现的名称.例如,要加载my.sql.Driver类,META-INF/services/java.sql.Driver文件将包含以下条目:
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
my.sql.Driver
应用程序不再需要使用Class.forName()显式加载JDBC驱动程序.当前使用Class.forName()加载JDBC驱动程序的现有程序将继续运行而无需进行修改.
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.
这篇关于为什么要使用Class.forName('database driver')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!