JDBC连结中Class.forName()详解

java开发中,采用JDBC连接数据库,最经常用到的就是Class.forName()这个方法.

Class.forName(String className)在JDK帮助文档中是这样说的:返回与带有给定字符串名的类或接口相关联的Class对象,

参数className是所需类的完全限定名;返回值是具有指定名的类的Class对象.如调用Class.forName("x") 将导致名为x的类被初始化.

 

JDBC连接中,以mysql为例,取得数据库连结代码如下:

DriverManager.getConnection()可以取到driver是因为Class.forName("...")方法已经要求JVM查找并加载指定的类(即com.mysql.jdbc.Driver类),而jdk对Driver的说明中有以下一段话:
     When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager

查看com.mysql.jdbc的原代码如下:

  

从而通过Class.forName(DriverString)会向DriverManager注册该Driver类.所以可以直接调用.

 

而Class.forName("").newInstance()则等于是将该Driver驱动类实例化,返回该类的一个实例,所以,如果只是取JDBC的Driver驱动,可

以不必用newInstance().

 

原话是这样的:

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.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值