连接到数据库时 Class.forName(“oracle.jdbc.driver.OracleDriver") 的实际用途是什么? [英] What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?
问题描述
命令是什么
Class.forName("oracle.jdbc.driver.OracleDriver")
在连接到 Oracle 数据库时到底要做什么?有没有其他方法可以做同样的事情?
exactly do while connecting to a Oracle database? Is there an alternate way of doing the same thing?
推荐答案
它获取对具有 FQCN(完全限定类名)oracle.jdbc.driver.OracleDriver
的类对象的引用.
It obtains a reference to the class object with the FQCN (fully qualified class name) oracle.jdbc.driver.OracleDriver
.
它不会做"连接到数据库方面的任何事情,除了确保指定的类由当前类加载器加载.写作没有本质区别
It doesn't "do" anything in terms of connecting to a database, aside from ensure that the specified class is loaded by the current classloader. There is no fundamental difference between writing
Class<?> driverClass = Class.forName("oracle.jdbc.driver.OracleDriver");
// and
Class<?> stringClass = Class.forName("java.lang.String");
Class.forName("com.example.some.jdbc.driver")
调用出现在使用 JDBC 的遗留代码中,因为 这是加载 JDBC 驱动程序的传统方式.
Class.forName("com.example.some.jdbc.driver")
calls show up in legacy code that uses JDBC because that is the legacy way of loading a JDBC driver.
来自Java 教程:
在以前的 JDBC 版本中,要获得连接,您首先必须通过调用方法 Class.forName
来初始化 JDBC 驱动程序.此方法需要 java.sql.Driver
类型的对象.每个 JDBC 驱动程序包含一个或多个实现接口 java.sql.Driver
.
...
在您的类路径中找到的任何 JDBC 4.0 驱动程序都会自动加载.(但是,您必须使用 Class.forName
方法手动加载 JDBC 4.0 之前的任何驱动程序.)
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 typejava.sql.Driver
. Each JDBC driver contains one or more classes that implements the interfacejava.sql.Driver
.
...
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 methodClass.forName
.)
进一步阅读(阅读:问题这是重复的)
- 目的是什么如果不使用返回值,Class.forName() 服务?
- Class.forName() 是如何工作的?
- 'Class.forName("org.sqlite.JDBC") 是什么?);'做什么?
- 'Class.forName("MY_JDBC_DRIVER"的目的是什么;)'?
- 加载 JDBC 驱动程序
这篇关于连接到数据库时 Class.forName(“oracle.jdbc.driver.OracleDriver") 的实际用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!