连接池

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();
            }
        }
    }
}

使用连接池,把暂时不使用的链接放入连接池,到需要使用的时候,从连接池中取出链接使用
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值