小白今天在连接数据库的时候,心里面突然想起之前有大佬说没有必要添加一条"com.mysql.jdbc.Driver",当时也实验了确实可行,但是这个可是驱动地址,难道是不用添加是根据驱动jar包自动识别出来吗?
开始了磕磕绊绊的探索,
public void connection4() throws Exception { //1.驱动地址,url,user,passwrod String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3307/mysql_test"; String user = "root"; String password = "root"; //2.建立驱动 Class<?> aClass = Class.forName(driverClassName); Driver driver = (Driver)aClass.newInstance();
//3.注册驱动 DriverManager.registerDriver(driver); //4.创建连接 Connection connection = DriverManager.getConnection(url,user,password); //在这里,我有个疑问,我想试着看一下通过DriverManager.registerDriver注册的驱动到底有几个? //01.先得到驱动 Enumeration<Driver> drivers = DriverManager.getDrivers(); int nums = 0; //使用while循环来遍历驱动的个数
while(drivers.hasMoreElements()) { nums ++; //打印出驱动 System.out.println(drivers.nextElement()); } //打印出驱动个数 System.out.println("驱动个数:" + nums); }
打印输出,发现居然有3个驱动,我自己只注册了1个。
带着个疑问,我试着注释了建立注册驱动。
public void connection4() throws Exception { //1.驱动地址,url,user,passwrod // String driverClassName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3307/mysql_test"; String user = "root"; String password = "root"; //2.建立驱动 // Class<?> aClass = Class.forName(driverClassName); // Driver driver = (Driver)aClass.newInstance(); // //3.注册驱动 DriverManger.registerDriver // DriverManager.registerDriver(driver); //4.创建连接 Connection connection = DriverManager.getConnection(url,user,password); //在这里,我有个疑问,我想试着看一下通过DriverManager.registerDriver注册的驱动到底有几个? //01.先得到驱动 Enumeration<Driver> drivers = DriverManager.getDrivers(); int nums = 0; //使用while循环来遍历驱动的个数 while(drivers.hasMoreElements()) { nums ++; //打印出驱动 System.out.println(drivers.nextElement()); } //打印出驱动个数 System.out.println("驱动个数:" + nums); }
问题来了,看来我只是注册了1个驱动,多余的两个是从哪里来的呢?
为此我去翻看了一下api文档里面关于DriverManager有这样一段话,
The DriverManager
methods getConnection
and getDrivers
have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver
. This file contains the name of the JDBC drivers implementation of java.sql.Driver
. For example, to load the my.sql.Driver
class, the META-INF/services/java.sql.Driver
file would contain the entry:(大概是在META-INF包里面包含了my.sql.Driver的类)
my.sql.Driver
Applications no longer need to explictly load JDBC drivers using Class.forName()
. Existing programs which currently load JDBC drivers using Class.forName()
will continue to work without modification.
When the method getConnection
is called, the DriverManager
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.
确实有两个驱动类,所以自动生成的两个驱动是从这里来的。。
后面大概是在讲,在JDBC 4.0以后 可以不用再很明确的去建立驱动,这样可以简化一些代码。
DriverManager使用过程中发现的问题得到解决。