是否需要 Class.forName() 机制? [英] Is Class.forName() mechanism needed?

查看:29
本文介绍了是否需要 Class.forName() 机制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

Class.forName(dbDriver); // "org.postgres.Driver" or "com.mysql.jdbc.Driver"

是/是打开 JDBC 连接所必需的.

is / was necessary to open JDBC connection.

我听说现代 JDBC 驱动程序不再需要它.但是,我无法在我的项目中删除它,因为我收到 找不到合适的驱动程序 异常.我正在使用 postgresql-9.1-901.jdbc3.jar、Java7 和 tomcat7.

I have heard that it is no longer needed with modern JDBC drivers. However I can't remove it in my project, because I'm getting No suitable driver found exception. I am using postgresql-9.1-901.jdbc3.jar, Java7 and tomcat7.

我什么时候可以省略 Class.forName(...) 构造?

When can I omit Class.forName(...) construct?

推荐答案

从 JDBC 4.0 开始不需要 Class.forName().

Class.forName() is not needed since JDBC 4.0.

这是关于 JDBC 的 Java 教程的摘录.

在以前版本的 JDBC 中,要获得连接,您首先必须通过调用 Class.forName 方法来初始化您的 JDBC 驱动程序.这方法需要一个 java.sql.Driver 类型的对象.每个 JDBC 驱动程序包含一个或多个实现接口的类java.sql.驱动程序.Java DB 的驱动程序是org.apache.derby.jdbc.EmbeddedDriver 和org.apache.derby.jdbc.ClientDriver,以及 MySQL Connector/J 的一个是 com.mysql.jdbc.Driver.请参阅 DBMS 驱动程序的文档以获取实现接口的类的名称java.sql.Driver.

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. This methods required an object of type java.sql.Driver. Each JDBC driver contains one or more classes that implements the interface java.sql.Driver. The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver, and the one for MySQL Connector/J is com.mysql.jdbc.Driver. See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver.

在您的类路径中找到的任何 JDBC 4.0 驱动程序都是自动加载.(但是,您必须手动加载任何驱动程序在 JDBC 4.0 之前使用 Class.forName 方法.)

Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

这篇关于是否需要 Class.forName() 机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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