JDBC连结中Class.forName()详解

来源:互联网 发布:大数据采集业务 编辑:程序博客网 时间:2024/05/17 22:29

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

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

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

 

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

[java] view plaincopyprint?
  1. Class.forName("com.mysql.jdbc.Driver");      
  2. String url = "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";      
  3. String user = "test";      
  4. String psw = "test";      
  5. Connection con = DriverManager.getConnection(url,user,psw);    

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的原代码如下:

[java] view plaincopyprint?
  1. package com.mysql.jdbc      
  2.      
  3. public class Driver extends NonRegisteringDriver implements java.sql.Driver {      
  4.  // ~ Static fields/initializers      
  5.  // --------------------------------------------- //      
  6.  // Register ourselves with the DriverManager      
  7.  //      
  8.  static {      
  9.     t ry {      
  10.               java.sql.DriverManager.registerDriver(new Driver());      
  11.           } catch (SQLException E) {      
  12.               throw new RuntimeException("Can't register driver!");      
  13.           }      
  14.   }      
  15. // ~ Constructors      
  16.  // -----------------------------------------------------------      
  17. /**    
  18.   * Construct a new driver and register it with DriverManager    
  19.   *     
  20.   * @throws SQLException    
  21.   *             if a database error occurs.    
  22.   */     
  23.  public Driver() throws SQLException {      
  24.      // Required for Class.forName().newInstance()      
  25.  }      
  26. }     
  

从而通过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 0