zoukankan      html  css  js  c++  java
  • 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#

  • 相关阅读:
    员工年龄排序之桶排序
    滑动窗口中最大值
    开机自动启动Tomcat
    基于RXTX的串口通讯 windows64位系统可用
    一些SQL
    Java 实现文件上传、下载、打包、文件copy、文件夹copy。
    Page-encoding specified in XML prolog (UTF-8) is different from that specified in page directive (utf-8)
    Java -> 把Excel表格中的数据写入数据库与从数据库中读出到本地 (未完善)
    (转)解决:本地计算机 上的 OracleOraDb10g_home1TNSListener服务启动后停止
    PHP、Java对称加密中的AES加密方法
  • 原文地址:https://www.cnblogs.com/phirothing/p/1863960.html
Copyright © 2011-2022 走看看