为什么JDBC动态加载而不是导入? [英] Why is JDBC dynamically loaded instead of imported?

查看:138
本文介绍了为什么JDBC动态加载而不是导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JDBC中,我只看到使用

In JDBC, I only see examples using

Class.forName("com.mysql.jdbc.Driver", true, cl);

并且没有看到使用

import com.mysql.jdbc.Driver;

是不是因为我们想在执行时动态提供驱动程序包,所以可以知道只在执行时?

Is it because we want to let a driver package be dynamically provided at execution time, so can be known only at execution time?

如果我们在执行前知道一个固定的驱动程序包,是否可以采用第二种方式?您如何比较这两种方式?

If we have a fixed driver package known before execution, is it possible to go with the second way? How would you compare the two ways?

谢谢。

推荐答案


我只看到使用

I only see examples using

然后你正在阅读关于JDBC的旧东西。在很长一段时间内,这已经没用了。在尝试这样做之前,加载驱动程序类以确保加载了必要的驱动程序并能够处理与提供的数据库URL的连接是

Then you're reading really old stuff about JDBC. This is not useful anymore, for quite a long time. It was necessary to load the driver class to make sure the necessary driver was loaded, and able to handle connections to the provided database URLs, before trying to do so.

JDBC抽象是访问数据库所需的全部内容,您无需关心是在处理MySQL驱动程序还是Oracle驱动程序,或者其他什么。在运行时动态加载驱动程序允许从编译类路径中删除驱动程序jar文件,并确保只依赖于标准JDBC类和接口。

The JDBC abstractions are all you need to access a database, and you shouldn't care whether you're dealing with a MySQL driver or an Oracle driver, or whatever. Loading the driver dynamically, at runtime, allows removing the driver jar file from the compile classpath, and making sure you only rely on the standard JDBC classes and interfaces.

注意导入类不会做任何事情,除了允许您在代码中使用简单的类名。它不等同于加载和初始化类,这是第一个代码片段的作用。

Note that importing a class doesn't do anything, other than allowing you to use the simple class name in your code. It's not equivalent to loading and initializing a class, which is what the first snippet does.

这篇关于为什么JDBC动态加载而不是导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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