当前位置: 代码迷 >> 综合 >> Java面试:数据源 javax.sql.DataSource
  详细解决方案

Java面试:数据源 javax.sql.DataSource

热度:80   发布时间:2024-01-10 16:17:31.0

DataSource数据源  是JDK1.4之后提供的用来获得连接的工厂,用来替代DriverManager。

数据库连接池:是一种具体的数据源的实现方式。

数据库连接池工作原理:  当服务器启动时,首先初始化一些链接放在连接池中,等待客户端请求链接,如果客户端请求链接了,首先查看连接池中是否有可用的链接,如果有则返回,如果没有则查看当前的连接数是否超过了最大可用链接,如果没有超过则创建新的链接返回给客户端,如果超过了,则等待,等待超时之后,抛出无可用链接的异常,最后当客户端使用完链接之后,再将链接放回到连接池中,从而实现链接的重用。

Apache-commons-DBCP组件:  采用了数据库连接池方案的数据源(javax.sql.DataSource)的具体实现组件(类库)

 

javax.sql.DataSource.java源码

package javax.sql;import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Wrapper;public interface DataSource  extends CommonDataSource, Wrapper {/*** <p>Attempts to establish a connection with the data source that* this {@code DataSource} object represents.** @return  a connection to the data source* @exception SQLException if a database access error occurs* @throws java.sql.SQLTimeoutException  when the driver has determined that the* timeout value specified by the {@code setLoginTimeout} method* has been exceeded and has at least tried to cancel the* current database connection attempt*/Connection getConnection() throws SQLException;/*** <p>Attempts to establish a connection with the data source that* this {@code DataSource} object represents.** @param username the database user on whose behalf the connection is*  being made* @param password the user's password* @return  a connection to the data source* @exception SQLException if a database access error occurs* @throws java.sql.SQLTimeoutException  when the driver has determined that the* timeout value specified by the {@code setLoginTimeout} method* has been exceeded and has at least tried to cancel the* current database connection attempt* @since 1.4*/Connection getConnection(String username, String password)throws SQLException;
}

 

org.apache.commons.dbcp

许多Apache项目都支持与关系数据库的交互。为每个用户创建新连接可能非常耗时(通常需要多秒的时钟时间),以便执行可能需要几毫秒的数据库事务。在公共托管的Internet应用程序中,每个用户打开一个连接可能是不可行的,因为同时用户的数量可能非常大。因此,开发人员通常希望在所有应用程序的当前用户之间共享打开连接的“池”。在任何给定时间实际执行请求的用户数通常占活动用户总数的很小百分比,并且在请求处理期间是唯一需要数据库连接的时间。应用程序本身登录到DBMS,并在内部处理任何用户帐户问题。

Apache产品和其他地方都有几个数据库连接池。此Commons软件包提供了一个机会,可以协调在ASF许可下创建和维护高效,功能丰富的软件包所需的工作。

BasicDataSource

常用属性:url username password driverClassName