zoukankan      html  css  js  c++  java
  • JDBC4.0版本后,不用再显式注册驱动

    一般写JDBC代码的时候都会有这么一句代码:

    1 Class.forName("com.mysql.jdbc.Driver");

    这是加载数据库的注册驱动。但是从JDBC4.0后,就不用显式加载了,也就是人家DriverManager类自动帮你加载了,这句代码你不用写了,直接获取数据库连接就行

    可以看下:java.sql.DriverManager 类中的注释:

    *<P> The <code>DriverManager</code> methods <code>getConnection</code> and
     * <code>getDrivers</code> have been enhanced to support the Java Standard Edition
     * <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">Service Provider</a> mechanism. JDBC 4.0 Drivers must
     * include the file <code>META-INF/services/java.sql.Driver</code>. This file contains the name of the JDBC drivers
     * implementation of <code>java.sql.Driver</code>.  For example, to load the <code>my.sql.Driver</code> class,
     * the <code>META-INF/services/java.sql.Driver</code> file would contain the entry:
     * <pre>
     * <code>my.sql.Driver</code>
     * </pre>
     *
     * <P>Applications no longer need to explicitly load JDBC drivers using <code>Class.forName()</code>. Existing programs
     * which currently load JDBC drivers using <code>Class.forName()</code> will continue to work without
     * modification.
    
    <P>When the method <code>getConnection</code> is called,
     * the <code>DriverManager</code> will attempt to
     * locate a suitable driver from amongst those loaded at
     * initialization and those loaded explicitly using the same classloader
     * as the current applet or application.

    着重看这一句话:

    1 * <P>Applications no longer need to explicitly load JDBC drivers using <code>Class.forName()</code>. Existing programs
    2  * which currently load JDBC drivers using <code>Class.forName()</code> will continue to work without
    3  * modification.

    上面的注释的意思就是说,JDBC4.0后必须包含:the file <code>META-INF/services/java.sql.Driver</code>这个文件,并且文件中必须有如下代码:

    <code>my.sql.Driver</code>

    我看了下我数据库jar包下对应的目录,确实有这个文件,而这个文件的内容确实有这段代码:

    在获取连接的时候,会自动的查找合适的驱动类,并初始化当前使用相同驱动的类。

    所以啊,就不劳我们费心自己手动加载注册驱动了:Class.forName("com.mysql.jdbc.Driver);不写也罢,当然,你想写也可以加上。

     但是在servlet类中的话,还是写上吧,下午测试,写这段代码,报:找不到合适的驱动的错误了。

  • 相关阅读:
    discuz X3.2 自定义系统广告详解
    windows平台myeclipse+PDT+apache+xdebug调试php
    南浮的IT民工
    linux实践——编译安装两个apache
    如何使maven+jetty运行时不锁定js和css[转]
    linux实践——ubuntu搭建 svn 服务
    测试代码插件(插入代码块)
    FTP 文件接口按天批处理脚本实例
    7月份工作小结
    报表开发过程
  • 原文地址:https://www.cnblogs.com/ljfsmile0613/p/13379877.html
Copyright © 2011-2022 走看看