• Java的jdbc中的Class.forName()和Class.forName().newInstance()


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

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

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

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

    Class.forName("com.mysql.jdbc.Driver");       
    String url = "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";       
    String user = "test";       
    String psw = "test";       
    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的原代码如下:

    代码
    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.


    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jackterq/archive/2009/08/24/4480745.aspx#

  • 相关阅读:
    Linux KVM
    linux 下添加,修改,删除路由
    爬虫之requests urllib urllib2 BeautifulSoup
    MyBatis-Plus+mysql5.7 动态拼接sql语句 分页查询 自定义sql 查询条件 分组 排序
    springboot2.x+neo4j创建图形数据库
    linux(centos7)下springboot项目jar包使用shell脚本运行
    java网络爬虫-利用phantomjs和jsoup爬取动态ajax加载页面
    springboot开发qq第三方授权登录
    linux(centos7)下nginx访问静态文件403错误解决过程
    idea2019.2+springboot2.2.1版本配置热部署
  • 原文地址:https://www.cnblogs.com/phirothing/p/1863960.html
Copyright © 2020-2023  润新知