您的位置:首页 > 数据库

数据库连接池的优点和原理

2014-05-07 13:30 363 查看
数据库连接是非常宝贵的系统资源,连接一次数据库,底层程序需要经过很多步骤,花费比较多的时间,如果每次要操作数据库的时候才开始建立数据库连接,用完之后再关闭连接,势必造成程序的效率问题。
连接池的基本原理是,先初始化一定的数据库连接对象,并且把这些连接保存在连接池中。当程序需要访问数据库的时候,从连接池中取出一个连接,数据库操作结束后,再把这个用完的连接重新放回连接池。
当然以上我说的是只是一个最简单的工作原理,连接池本身是比较复杂的,里面涉及到并发的控制,连接的提取,回收算法,连接不够时的相应等等。

package test;
import java.sql.*;
import java.util.*;

public class DBConnpool
{
private int inUse = 0;
private Vector<Connection> connections = new Vector<Connection>();
private String poolname = "dbconnpool";
private String dbid = "jdbc:mysql://localhost:3306/teasystem";
private String drivername = "com.mysql.jdbc.Driver";
private String username = "root";
private String password = "123";
private int maxconn = 5000;

public DBConnpool(){}
public void setdbid(String dbid)
{
this.dbid = dbid;
}
public void setusername(String username)
{
this.username = username;
}
public void setpassword(String password)
{
this.password = password;
}
public void setmaxconn(int maxconn)
{
this.maxconn = maxconn;
}
public String getdbid()
{
return dbid;
}
public String getusername()
{
return username;
}
public String getpassword()
{
return password;
}
public int getmaxconn()
{
return maxconn;
}
//将连接返还给连接池
public synchronized void reConnection(Connection conn)
{
Connection con = conn;
connections.addElement(con);
inUse--;
}
//从连接池获取一个连接
public synchronized Connection getConnection()
{
Connection con = null;
if(connections.size()>0)
{
con = (Connection)connections.elementAt(0);
connections.removeElementAt(0);
try{
if(con.isClosed())
{
con = getConnection();
}
}catch(Exception e){
e.printStackTrace();
}
}else if(maxconn == 0||inUse<maxconn)
{
con = newConnection();
}
if(con != null)
{
inUse++;
}
return con;
}
private Connection newConnection()
{
Connection con = null;
try{
Class.forName(drivername);
con = DriverManager.getConnection(dbid,username,password);
}catch(Exception e){
e.printStackTrace();
return null;
}
return con;
}
public synchronized void closeConn()
{
Enumeration allConnections = connections.elements();
while(allConnections.hasMoreElements())
{
Connection con = (Connection)allConnections.nextElement();
try{
con.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}

使用连接池,把暂时不使用的链接放入连接池,到需要使用的时候,从连接池中取出链接使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息