java 几种加载驱动的方法

Python011

java 几种加载驱动的方法,第1张

三种加载方式

1.Class.forName(“com.mysql.jdbc.Driver”)

2.DriverManager.registerDriver(new com.mysql.jdbc.Driver())

3.System.setProperty(“jdbc.drivers”,”com.mysql.jdbc.Driver”)

的是为了实例化对象。

Class.forName("")返回的是类

Class.forName("").newInstance()返回的是object

刚才提到,Class.forName("")的作用是要求JVM查找并加载指定的类,如果在类中有静态初始化器的话,JVM必然会执行该类的静态代码 段。而在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,即任何一个JDBC Driver的 Driver类的代码都必须类似如下:

public class MyJDBCDriver implements Driver {static {DriverManager.registerDriver(new MyJDBCDriver())}}既然在静态初始化器的中已经进行了注册,所以我们在使用JDBC时只需要Class.forName(XXX.XXX)就可以了。

we just want to load the driver to jvm only, but not need to user the instance of driver, so call Class.forName(xxx.xx.xx) is enough, if you call Class.forName(xxx.xx.xx).newInstance(), the result will same as calling Class.forName(xxx.xx.xx), because Class.forName(xxx.xx.xx).newInstance() will load driver first, and then create instance, but the instacne you will never use in usual, so you need not to create it.

总结:jdbc数据库驱动程序最终的目的,是为了程序员能拿到数据库连接,而进行jdbc规范的数据库操作。拿到连接的过程是不需要你自己来实例化驱动程序的,而是通过 DriverManger.getConnection(string str)。因此一般情况下,对于程序员来说,除非特别需求,是不会自己去实例化一个数据库驱动使用里面的方法的。