• JDBC创建mysql连接池代码


    1、底层实现类(DBConnection)

      

      1 package JDBC.JDBCPool.MyJDBCPool;
      2 
      3 import java.sql.Connection;
      4 import java.sql.DriverManager;
      5 import java.sql.SQLException;
      6 import java.util.Enumeration;
      7 import java.util.Vector;
      8 
      9 /**
     10  * Created by Administrator on 2018/3/10 0010.
     11  */
     12 public class DBConnection {
     13     private String password;
     14     private String url;
     15     private String user;
     16     private int normalConn;
     17     private int maxConn;
     18     private Vector<Connection> freeConnections = new Vector<Connection>();
     19     private static int num = 0;// 空闲的连接数
     20     private static int numActive = 0;// 当前的连接数
     21     private int checkedOut;
     22 
     23     public DBConnection(String password, String url, String user,
     24                             int normalConn, int maxConn) {
     25         this.password = password;
     26         this.url = url;
     27         this.user = user;
     28         this.maxConn = maxConn;
     29         this.normalConn = normalConn;
     30         for (int i = 0; i < normalConn; i++) { // 初始normalConn个连接
     31             Connection c = newConnection();
     32             if (c != null) {
     33                 freeConnections.addElement(c);
     34                 num++;
     35             }
     36         }
     37     }
     38     // 创建一个新连接
     39 
     40     private Connection newConnection() {
     41         Connection con = null;
     42         try {
     43             if (user == null) { // 用户,密码都为空
     44                 con = DriverManager.getConnection(url);
     45             } else {
     46                 con = DriverManager.getConnection(url, user, password);
     47             }
     48             System.out.println("连接池创建一个新的连接");
     49         } catch (SQLException e) {
     50             System.out.println("无法创建这个URL的连接" + url);
     51             return null;
     52         }
     53         return con;
     54     }
     55 
     56     public synchronized Connection getConnection() {
     57       Connection con=null;
     58       if(freeConnections.size()>0) {
     59           num--;//调用之后,空闲的连接就减少一个
     60           con = (Connection) freeConnections.firstElement();
     61           freeConnections.removeElementAt(0);
     62           try {
     63               if (con.isClosed()) {
     64                   System.out.println("从连接池删除了一个无效连接");
     65                   con = getConnection();
     66               }
     67           } catch (SQLException e) {
     68               System.out.println("从连接池删除了一个无效连接");
     69               con = getConnection();
     70           }
     71       }else if(maxConn==0||checkedOut<maxConn){
     72           con=newConnection();
     73       }
     74       if(con!=null){//当前连接数+1
     75             checkedOut++;
     76       }
     77       numActive++;
     78       return con;
     79     }
     80 
     81     public int getnumActive() {
     82         return numActive;
     83     }
     84 
     85     public int getnum(){//获取空闲连接数目
     86         return num;
     87     }
     88 
     89     public synchronized  void release(){
     90         Enumeration allConnections=freeConnections.elements();
     91         while(allConnections.hasMoreElements()){
     92             Connection con=(Connection)allConnections.nextElement();
     93             try {
     94                 con.close();
     95                 num--;
     96             } catch (SQLException e) {
     97                 System.out.println("无法关闭连接池中的连接");
     98             }
     99         }
    100         freeConnections.removeAllElements();
    101         numActive=0;
    102     }//释放空闲的链接
    103 
    104     public synchronized  void freeConnection(Connection con){
    105         freeConnections.addElement(con);
    106         num++;//空闲的链接增加一个
    107         checkedOut--;
    108         numActive--;
    109         notifyAll();
    110     }
    111 }

    2、连接池接口代码

      

     1 package JDBC.JDBCPool.MyJDBCPool;
     2 
     3 
     4 import java.sql.Connection;
     5 import java.sql.Driver;
     6 import java.sql.DriverManager;
     7 import java.sql.SQLException;
     8 
     9 /**
    10  * Created by Administrator on 2018/3/10 0010.
    11  */
    12 public class DBPool {
    13     private String password = "root";// 密码
    14     private String url = "jdbc:mysql://localhost/bz?useSSL=false";// 连接URL
    15     private String user = "root";// 用户名
    16     private String driverName = "com.mysql.jdbc.Driver";// 驱动类
    17     private int normalConnect = 10;// 保持连接数
    18     private int maxConn=0;
    19     private DBConnection dbPool=null;
    20     private static DBPool instance = null; // 定义唯一实例
    21     Driver driver = null;// 驱动变量
    22 
    23     private DBPool(){
    24         loadDrivers(driverName);
    25         createPool();
    26     }
    27 
    28     public void loadDrivers(String driverName){
    29         String driverClassName=driverName;
    30         try {
    31             driver =(Driver)Class.forName(driverClassName).newInstance();
    32             DriverManager.registerDriver(driver);//注册驱动需要的是驱动程序的实例
    33             System.out.println("成功注册JDBC驱动程序" + driverClassName);
    34         } catch(Exception e){
    35             System.out.println("注册JDBC驱动程序失败");
    36         }
    37     }
    38 
    39     public void createPool(){
    40         dbPool=new DBConnection(password,url,user,normalConnect,maxConn);
    41         if(dbPool!=null){
    42             System.out.println("数据库连接池成功创建");
    43         }else{
    44             System.out.println("数据库连接池创建失败");
    45         }
    46     }//创建一个连接池
    47 
    48     public static synchronized DBPool getInstance() {
    49         if (instance == null) {
    50             instance = new DBPool();
    51         }
    52         return instance;
    53     }//调用构造函数返回一个独有的连接池
    54 
    55     public Connection getConnection() {
    56         if (dbPool!= null) {
    57             return dbPool.getConnection();
    58         }
    59         return null;
    60     }
    61 
    62     public int getnumActive() {
    63         return dbPool.getnumActive();
    64     }//获取有效连接数目
    65 
    66     public int getnum(){
    67         return dbPool.getnum();
    68     }//获取空闲连接数目
    69 
    70     public void freeConnection(Connection con) {
    71         if (dbPool != null) {
    72             dbPool.freeConnection(con);
    73         }
    74     }
    75 
    76     public synchronized void release(){
    77         dbPool.release();
    78         try {
    79             DriverManager.deregisterDriver(driver);
    80             System.out.println("撤销JDBC驱动程序"+driver.getClass().getName()+"成功");
    81         } catch (SQLException e) {
    82             System.out.println("无法撤销JDBC驱动程序的注册:"+driver.getClass().getName());
    83         }
    84     }
    85 }

    三、测试类

      

    package JDBC.JDBCPool.MyJDBCPool;
    
    import java.sql.Connection;
    
    /**
     * Created by Administrator on 2018/3/10 0010.
     */
    public class Test {
        public Test(){}
    
        public static void main(String[] args) {
            DBPool dbPool=DBPool.getInstance();
            System.out.println(dbPool.getnumActive());
            System.out.println(dbPool.getnum());
            Connection con1=dbPool.getConnection();
            System.out.println(dbPool.getnumActive());
            System.out.println(dbPool.getnum());
            dbPool.release();
        }
    }
  • 相关阅读:
    js 日期比较 (输入的是字符串格式)
    js 弹出确认 取消对话框
    存储过程中查询多个字段的值来判断
    SQL中IF查询
    SQL server 2000安装时提示我”以前的某个程序安装已在安装计算机上创建挂起的文件操
    怎样做人
    RSS
    Silverlight教程第四部分:使用 Style 元素更好地封装观感 (木野狐译)
    Silverlight 2 初览
    Silverlight教程第七部分: 使用控件模板定制控件的观感
  • 原文地址:https://www.cnblogs.com/television/p/8538743.html
Copyright © 2020-2023  润新知