为什么我们使用DataSource而不是DriverManager? [英] Why do we use a DataSource instead of a DriverManager?

查看:274
本文介绍了为什么我们使用DataSource而不是DriverManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Java JDBC规范(vr.4)并且我声明了这句话:

I am reading the Java JDBC specification (vr. 4) and I encountred this statement:


DataSource - 此接口是在JDBC 2.0可选
包API。它比DriverManager更受欢迎,因为它允许
有关底层数据源的详细信息对
应用程序是透明的

DataSource — this interface was introduced in the JDBC 2.0 Optional Package API. It is preferred over DriverManager because it allows details about the underlying data source to be transparent to the application

我想要了解的是 连接 DataSource ,以及它存在的原因。我的意思是,上面的块表示有关数据源的详细信息对应用程序是透明的,但不会在属性文件中外部化数据库属性(如用户名,密码,URL等),然后以相同的方式使用DriverManager工作?

What I am trying to understand is what the difference is between a Connection and a DataSource, and why it exists. I mean, the block above says that the details about a datasource is transparent to the application, but wouldn't externalizing database properties such as username, password, url etc in a property file and then use DriverManager work in the same way?

并且是 DataSource 创建的界面只是为了有一个返回可以合并的连接的常用方法等?在Java EE中,应用程序服务器是否实现了此接口,部署的应用程序是否引用了数据源而不是连接?

And is the DataSource interface created only to have a common way of returning connections that can be pooled etc? In Java EE, does the application server implement this interface and the applications deployed to have a reference to a datasource instead of a connection?

推荐答案

更好的可扩展性和维护

对于驱动程序管理器,您需要知道连接到数据库的所有细节(主机,端口,用户名,密码,驱动程序类)并获取连接。外部化属性文件中的内容并不会改变您需要了解它们的任何事实。

For driver manager you need to know all the details (host, port, username, password, driver class) to connect to DB and to get connections. Externalizing those in a properties file doesn't change anything about the fact that you need to know them.

使用DataSource只需要知道JNDI名称。 AppServer关注细节,并不是由客户端应用程序的供应商配置,而是由托管应用程序的管理员配置。

Using a DataSource you only need to know the JNDI name. The AppServer cares about the details and is not configured by the client application's vendor, but by an admin where the application is hosted.

可伸缩性:

假设你需要自己创建连接,你将如何处理不断变化的负载,有时当你有1000个用户时有10个用户,你不能在需要的时候获得连接,以后再发布'因此,数据库服务器不会脱离连接,从而导致连接池。 DriverManager不提供它,DataSource不提供。

Suppose you need to create connections yourself, how would you deal with changing load, sometime you have 10 users sometime you have 1000, you can't just get a connection whenever you need one and later 'release' it so the Database server does not get out of connections, which leads you to connection pooling. DriverManager does not provide it, DataSource does.

如果要编写连接池,则必须使用DriverManager,否则请使用DataSource。

If you are going to program a connection pool then you have to use DriverManager, otherwise go with DataSource.

这篇关于为什么我们使用DataSource而不是DriverManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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