为什么调用Class.forName(" com.mysql.jdbc.Driver")为JDBC注册MySQL? [英] Why does calling Class.forName("com.mysql.jdbc.Driver") register the MySQL for JDBC?

查看:199
本文介绍了为什么调用Class.forName(" com.mysql.jdbc.Driver")为JDBC注册MySQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别在Class.forName()之间和Class.forName()。newInstance()"?,方法Class.forName()执行以下操作:

As explained in What is the difference between "Class.forName()" and "Class.forName().newInstance()"?, the method Class.forName() does the following:

调用Class.forName(String)返回与具有给定字符串名称的类或接口关联的Class对象

但是,如果它只是这样做,为什么是那么有必要调用这个方法以便在Java中使用MySQL吗?没有它我得到以下错误:

But, if it only does that, why is it then neccesary to call this method in order to use MySQL with Java? Without it I get the following error:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/calender
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at Database.main(Database.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)


推荐答案

它注册它是因为它将类加载到内存中并运行类的静态初始化程序。然后静态初始化代码调用JDBC框架说你好,我是JDBC驱动程序(通过调用 DriverManager.registerDriver )。

It registers it because it loads the class into memory and runs the class's static initializers. The static initializer code then calls into the JDBC framework to say "Hi there, I'm a JDBC driver" (by calling DriverManager.registerDriver).

例如,驱动程序类看起来像含糊不清

E.g., the driver class will look vaguely like this:

package com.example.jdbc;

import java.sql.DriverManager;

public class Driver implements java.sql.Driver {
    static {
        DriverManager.registerDriver(new Driver());
    }

    // ...implementation...
}

然后当你执行 Class.forName(com.example.jdbc.Driver)时,它会加载该类并运行静态初始化程序,一个实例并使用 DriverManager 注册它。

Then when you do Class.forName("com.example.jdbc.Driver"), it loads the class and runs the static initializer, which creates an instance and registers it with the DriverManager.

我应该请注意正如Andreas所说,现代JDBC驱动程序不需要你这样做。

I should note that as Andreas says, modern JDBC drivers don't need you to do this.

这篇关于为什么调用Class.forName(" com.mysql.jdbc.Driver")为JDBC注册MySQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆