JAVA寫簡單的數據庫連接池


創建數據庫連接以及關閉連接是很耗費時間的,並且數據庫支持的連接數量也是有限的,當數據庫的連接數量達到上限的時候,后續的連接就會失敗。因此這里引入了數據庫緩沖池。

public class ConnecionPool {
    private int size;
    List<Connection> connections = new ArrayList<>();
    public ConnecionPool(int size){
        this.size=size;
        init();
    }
    public void init(){

        try {
            Class.forName("com.mysql.jdbc.Driver");
            while (size--!=0){

                connections.add(DriverManager.getConnection(jdbc:mysql://127.0.0.1:3306/d數據庫名稱, 用戶名,密碼)// );

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public Connection getConnection(){
        try {//如果沒有連接了,線程就等待
            while (connections.isEmpty()){
                this.wait();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return connections.remove(0);
    }
    public void returnConntion(Connection connection){
        connections.add(connection);
        this.notifyAll();
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM