首先说明一下,这个数据库链接池不是我写的。是我在网上找到的,由于代码并不全,因此进行了一些填充。可以正常运行了。所以贴出来希望能帮到需要的人。
这个数据库链接池的好处在于当用户从数据库链接池中的到连接后,并不需要特殊的方法将链接关闭,直接用close方法就可以关闭了。废话少说,上代码!!!!
再次说明一下,以下的代码是根据网上得到的部分代码填充得到的,并不代表没有错误。如果那位高手能将代码完善感激不尽。
下面的一段代码是一些数据库的属性。
java 代码
- public class ConnectionParam {
- private String driver = null; //数据库驱动程序
- private String host = null; //数据连接的URL
- private String user = null; //数据库用户名
- private String password = null; //数据库密码
- private String dataBase= null;
- private String url = null;
- private int minConnection = 0; //初始化连接数
- private int maxConnection = 0; //最大连接数
- private long timeoutValue = 0; //连接的最大空闲时间
- private long waitTime = 0; //取连接的时候如果没有可用连接最大的等待时间
- public ConnectionParam(){
- super();
- try {
- String tmp = null;
- int value = 0;
- //CommonUtil.getPropertie("");方法是自己写的一个从属性文件中读取信息的方法。
- this.driver = CommonUtil.getPropertie("driver");
- this.host = CommonUtil.getPropertie("host");
- this.user = CommonUtil.getPropertie("user");
- this.password = CommonUtil.getPropertie("password");
- this.dataBase= CommonUtil.getPropertie("dataBase");
- this.url =CommonUtil.getPropertie("url");
- tmp = CommonUtil.getPropertie("maxConnection");
- value = 0;
- if(CommonUtil.isNull(tmp)){
- value = 0;
- }else{
- value = Integer.parseInt(tmp);
- }
- this.maxConnection = value;
- tmp = CommonUtil.getPropertie("timeoutValue");
- value = 0;
- if(CommonUtil.isNull(tmp)){
- value = 0;
- }else{
- value = Integer.parseInt(tmp);
- }
- this.timeoutValue = value;
- tmp = CommonUtil.getPropertie("waitTime");
- value = 0;
- if(CommonUtil.isNull(tmp)){
- value = 0;
- }else{
- value = Integer.parseInt(tmp);
- }
- this.waitTime = value;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
下面这段代码是实现连接池的,其中的一些方法并没有实现。请各位见谅。
java 代码
- import java.io.PrintWriter;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import javax.sql.DataSource;
- public class DataSourceImpl implements DataSource {
- private ConnectionParam connParam = null;
- private List conns = null;
- public DataSourceImpl(ConnectionParam param){
- conns = new ArrayList();
- this.connParam = param;
- }
- public Connection getConnection() throws SQLException {
- //首先从连接池中找出空闲的对象
- Connection conn = getFreeConnection(0);
- Connection conn2 = null;
- if(conn == null){
- //判断是否超过最大连接数,如果超过最大连接数
- //则等待一定时间查看是否有空闲连接,否则抛出异常告诉用户无可用连接
- if(getConnectionCount() >= connParam.getMaxConnection())
- conn = getFreeConnection(connParam.getWaitTime());
- else{//没有超过连接数,重新获取一个数据库的连接
- try {
- Class.forName(connParam.getDriver()).newInstance();
- conn2 = DriverManager.getConnection(connParam.getUrl(),
- connParam.getUser(), connParam.getPassword());
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- //代理将要返回的连接对象
- _Connection _conn = new _Connection(conn2,true);
- synchronized(conns){
- conns.add(_conn);
- }
- conn = _conn.getConnection();
- }
- }
- return conn;
- }
- public Connection getConnection(String username, String password)
- throws SQLException {
- //首先从连接池中找出空闲的对象
- Connection conn = getFreeConnection(0);
- Connection conn2 = null;
- if(conn == null){
- //判断是否超过最大连接数,如果超过最大连接数
- //则等待一定时间查看是否有空闲连接,否则抛出异常告诉用户无可用连接
- if(getConnectionCount() >= connParam.getMaxConnection())
- conn = getFreeConnection(connParam.getWaitTime());
- else{//没有超过连接数,重新获取一个数据库的连接
- connParam.setUser(username);
- connParam.setPassword(password);
- try {
- Class.forName(connParam.getDriver()).newInstance();
- conn2 = DriverManager.getConnection(connParam.getUrl(),
- username, password);
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //代理将要返回的连接对象
- _Connection _conn = new _Connection(conn2,true);
- synchronized(conns){
- conns.add(_conn);
- }
- conn = _conn.getConnection();
- }
- }
- return conn;
- }
- public PrintWriter getLogWriter() throws SQLException {
- // TODO Auto-generated method stub
- return null;
- }
- public int getLoginTimeout() throws SQLException {
- // TODO Auto-generated method stub
- return 0;
- }
- public void setLogWriter(PrintWriter out) throws SQLException {
- // TODO Auto-generated method stub
- }
- public void setLoginTimeout(int seconds) throws SQLException {
- // TODO Auto-generated method stub
- }
- public void initConnection(){
- // TODO Auto-generated method stub
- }
- public void stop(){
- // TODO Auto-generated method stub
- }
- /**
- * 从连接池中取一个空闲的连接
- * @param nTimeout 如果该参数值为0则没有连接时只是返回一个null
- * 否则的话等待nTimeout毫秒看是否还有空闲连接,如果没有抛出异常
- * @return Connection
- * @throws SQLException
- */
- protected synchronized Connection getFreeConnection(long nTimeout)
- throws SQLException
- {
- Connection conn = null;
- Iterator iter = conns.iterator();
- while(iter.hasNext()){
- _Connection _conn = (_Connection)iter.next();
- if(!_conn.isInUse()){
- conn = _conn.getConnection();
- _conn.setInUse(true);
- break;
- }
- }
- if(conn == null && nTimeout > 0){
- //等待nTimeout毫秒以便看是否有空闲连接
- try{
- Thread.sleep(nTimeout);
- }catch(Exception e){}
- conn = getFreeConnection(0);
- if(conn == null)
- throw new SQLException("没有可用的数据库连接");
- }
- return conn;
- }
- /**
- * 关闭该连接池中的所有数据库连接
- * @return int 返回被关闭连接的个数
- * @throws SQLException
- */
- public int close() throws SQLException
- {
- int cc = 0;
- SQLException excp = null;
- Iterator iter = conns.iterator();
- while(iter.hasNext()){
- try{
- ((_Connection)iter.next()).close();
- cc ++;
- }catch(Exception e){
- if(e instanceof SQLException)
- excp = (SQLException)e;
- }
- }
- if(excp != null)
- throw excp;
- return cc;
- }
- /**
- * 返回当前链接的个数
- * @return
- */
- private int getConnectionCount(){
- Iterator iter = conns.iterator();
- int count = 0;
- while(iter.hasNext()){
- _Connection _conn = (_Connection)iter.next();
- if(_conn.isInUse()){
- count++;
- }
- }
- return count;
- }
- }
下面的是一个代理类。用来实现直接用close关闭连接。
java 代码
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.sql.Connection;
- import java.sql.SQLException;
- public class _Connection implements InvocationHandler {
- private final static String CLOSE_METHOD_NAME = "close";
- private Connection conn = null;
- //数据库的忙状态
- private boolean inUse = false;
- //用户最后一次访问该连接方法的时间
- private long lastAccessTime = System.currentTimeMillis();
- _Connection(Connection conn, boolean inUse){
- this.conn = conn;
- this.inUse = inUse;
- }
- /**
- * Returns the conn.
- * @return Connection
- */
- public Connection getConnection() {
- //返回数据库连接conn的接管类,以便截住close方法
- Connection conn2 = (Connection)Proxy.newProxyInstance(
- conn.getClass().getClassLoader(),
- conn.getClass().getInterfaces(),this);
- return conn2;
- }
- /**
- * 该方法真正的关闭了数据库的连接
- * @throws SQLException
- */
- void close() throws SQLException{
- //由于类属性conn是没有被接管的连接,因此一旦调用close方法后就直接关闭连接
- conn.close();
- }
- /**
- * Returns the inUse.
- * @return boolean
- */
- public boolean isInUse() {
- return inUse;
- }
- /**
- * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object)
- */
- public Object invoke(Object proxy, Method m, Object[] args)
- throws Throwable
- {
- Object obj = null;
- //判断是否调用了close的方法,如果调用close方法则把连接置为无用状态
- if(CLOSE_METHOD_NAME.equals(m.getName()))
- setInUse(false);
- else
- obj = m.invoke(conn, args);
- //设置最后一次访问时间,以便及时清除超时的连接
- lastAccessTime = System.currentTimeMillis();
- return obj;
- }
- /**
- * Returns the lastAccessTime.
- * @return long
- */
- public long getLastAccessTime() {
- return lastAccessTime;
- }
- /**
- * Sets the inUse.
- * @param inUse The inUse to set
- */
- public void setInUse(boolean inUse) {
- &
本文介绍了一个简单的数据库连接池实现方案。通过此方案,开发者能够更高效地管理和使用数据库连接资源,无需显式关闭连接。文章提供了部分核心代码示例,包括连接池的基本配置和连接管理逻辑。
1万+

被折叠的 条评论
为什么被折叠?



