码迷,mamicode.com
首页 > 数据库 > 详细

JDBC4.0版本后,不用再显式注册驱动

时间:2020-07-26 15:41:48      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:loader   support   exist   nta   并且   edit   imp   src   inf   

一般写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);不写也罢,当然,你想写也可以加上。

 

JDBC4.0版本后,不用再显式注册驱动

标签:loader   support   exist   nta   并且   edit   imp   src   inf   

原文地址:https://www.cnblogs.com/ljfsmile0613/p/13379877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!