• 用java代码实现,简易连接池


    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;

    public class ConnectionPool {
      private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";          //驱动类
      private static final String URL = "jdbc:sqlserver://192.168.0.200:1433;databaseName=MIFUWEBDB";   //数据库url
      private static final String USER = "sa";                                     
      private static final String PASSWORD = "123456";

      private static final int MAXPOOL = 100; //最大连接数
      private static final int MINPOOL = 10; //最小连接数
      private static List pool = new LinkedList(); //连接池对象

      public ConnectionPool(){
        init();
      }

      private void init(){                                           //初始化
        try {
          Class.forName(DRIVER);
          for(int i=0; i<MINPOOL; i++){
            Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
            pool.add(con);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      public synchronized Connection getCon(){                               //获取连接
        while(pool.isEmpty()){
          try {
            this.wait();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        Connection con = (Connection) pool.remove(0);
        return con;
      }

      public synchronized void returnCon(Connection con){                          //释放连接
        if(con!=null){
          pool.add(con);
        }
        this.notifyAll();
      }

    }

  • 相关阅读:
    剑指offer 把字符串转换成整数 python
    剑指offer 重建二叉树 python
    LeetCode 82 删除排序链表中的重复元素 II python
    LeetCode 142 环形链表 II python
    hashlib
    configparser
    正则
    logging
    模块
    文件操作
  • 原文地址:https://www.cnblogs.com/liuqu/p/8661938.html
Copyright © 2020-2023  润新知