zoukankan      html  css  js  c++  java
  • 自定义JDBC链接池

    上篇简单介绍了jdbc链接数据库

    本篇就说一下自定义连接池以及增删改查的测试

    自定义连接池

    自定义链接池的原因

        JDBC连接中用到Connection   在每次对数据进行增删查改 都要 开启  、关闭  ,在开发项目中 ,浪费了很大的资源 ,所以我们自己定义了一个连接池,用池来管理Connection,这样可以重复使用Connection,有了池,我们就不用自己来创建Connection,而是通过池来获取Connection对象,当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池,池也就可以再利用这个Connection对象。

     

    创建自定义连接池的步骤

    1 创建连接池实现(数据源),并实现接口javax.sql.DataSource.

    2 提供一个集合,用于存放连接,因为移除/添加操作过多,所以选用LinkedList较好

    3 为连接池初始化连接

    4 程序如果需要连接,调用实现类的getConnection(),本方法将从连接池(容器List)获取连接,为了保证当前连接只是停工给一个线程使用,我们需要将连接先从连接池中移除。

    5 当用户使用完连接,释放资源时,不执行close()方法,而是将连接添加到连接池中

    自定义连接池的代码:

      1 package com.baidu.database.tools;
      2 
      3 import java.io.PrintWriter;
      4 import java.lang.reflect.InvocationHandler;
      5 import java.lang.reflect.Method;
      6 import java.lang.reflect.Proxy;
      7 import java.sql.Connection;
      8 import java.sql.SQLException;
      9 import java.sql.SQLFeatureNotSupportedException;
     10 import java.util.LinkedList;
     11 import java.util.logging.Logger;
     12 
     13 import javax.sql.DataSource;
     14 
     15 /**
     16  * 自定义连接池
     17  * 
     18  * @author Admin
     19  *
     20  */
     21 public class MyDatabasePool implements DataSource {
     22 
     23     /**
     24      * 创建集合存放连接
     25      */
     26     public LinkedList<Connection> list = new LinkedList<>();
     27 
     28     // 使用构造方法初始化连接池
     29     public MyDatabasePool() throws Exception {
     30         // 创建最小连接数个数据库连接对象以备使用
     31         for (int i = 1; i < 21; i++) {
     32             // 将创建好的数据库连接对象添加到Linkedlist集合中
     33             list.add(JdbcUtils.getConnection());
     34         }
     35     }
     36 
     37     @Override
     38     public void setLogWriter(PrintWriter out) throws SQLException {
     39         // TODO Auto-generated method stub
     40 
     41     }
     42 
     43     @Override
     44     public void setLoginTimeout(int seconds) throws SQLException {
     45         // TODO Auto-generated method stub
     46 
     47     }
     48 
     49     @Override
     50     public int getLoginTimeout() throws SQLException {
     51         // TODO Auto-generated method stub
     52         return 0;
     53     }
     54 
     55     @Override
     56     public Logger getParentLogger() throws SQLFeatureNotSupportedException {
     57         // TODO Auto-generated method stub
     58         return null;
     59     }
     60 
     61     @Override
     62     public <T> T unwrap(Class<T> iface) throws SQLException {
     63         // TODO Auto-generated method stub
     64         return null;
     65     }
     66 
     67     @Override
     68     public boolean isWrapperFor(Class<?> iface) throws SQLException {
     69         // TODO Auto-generated method stub
     70         return false;
     71     }
     72 
     73     /**
     74      * 获取链接 通过动态代理(Proxy)实现的数据库连接池的创建连接与归还链接的操作
     75      */
     76     @Override
     77     public Connection getConnection() throws SQLException {
     78         Connection connection = list.removeLast();
     79         //创建代理对象
     80         Connection proxyConnection = (Connection) Proxy.newProxyInstance(
     81                 //类加载器
     82                 connection.getClass().getClassLoader(),
     83                 //目标接口对象
     84                 new Class[] { Connection.class },
     85                 //当调用connction对象的时候自动触发事务处理器
     86                 new InvocationHandler() {
     87                     @Override
     88                     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
     89                         //判断执行close()就把连接放入连接池
     90                         if ("close".equals(method.getName())) {
     91                             //连接放入连接池
     92                             list.addLast(connection);
     93                             return null;
     94                         } else {
     95                              //调用目标方法对象
     96                             return method.invoke(connection, args);
     97                         }
     98 
     99                     }
    100                 });
    101         return proxyConnection;
    102 
    103     }
    104 
    105     @Override
    106     public Connection getConnection(String username, String password) throws SQLException {
    107         // TODO Auto-generated method stub
    108         return null;
    109     }
    110 
    111     @Override
    112     public PrintWriter getLogWriter() throws SQLException {
    113         // TODO Auto-generated method stub
    114         return null;
    115     }
    116 
    117 }
              JdbcUtils地址

    ★测试增删改查:

      1 package com.baidu.database.test;
      2 
      3 import java.sql.Connection;
      4 import java.sql.PreparedStatement;
      5 import java.sql.ResultSet;
      6 
      7 import org.junit.After;
      8 import org.junit.Before;
      9 import org.junit.Test;
     10 
     11 import com.baidu.database.tools.JdbcUtils;
     12 import com.baidu.database.tools.MyDatabasePool;
     13 
     14 public class MySouceTest {
     15 
     16     // 初始化value
     17     static  MyDatabasePool database = null;
     18     static Connection connection = null;
     19     static PreparedStatement statement = null;
     20     static ResultSet result = null;
     21     @Before
     22     public void StartDocument() throws Exception {
     23         // 创建自定义数据库对象
     24         database = new MyDatabasePool();
     25     }
     26 
     27     @After
     28     public void end() throws Exception {
     29         // 关闭链接
     30         JdbcUtils.close(connection, statement, result);
     31         System.out.println("关闭链接");
     32     }
     33     
     34     @Test
     35     /**
     36      * 测试添加功能
     37      * 
     38      * @throws Exception
     39      */
     40     public void addTest() throws Exception {
     41         // 获取链接
     42         connection = database.getConnection();
     43         // 书写SQL语句
     44         String sql = "insert into test01 values(?,?)";
     45         // 使用prepareStatement对象进行预编译
     46         statement = connection.prepareStatement(sql);
     47         // 设置参数
     48         statement.setInt(1, 1);
     49         statement.setString(2, "张三");
     50         // 获取结果
     51         int result = statement.executeUpdate();
     52 
     53         if (result != 0) {
     54             System.out.println("success");
     55         }
     56     }
     57 
     58     @Test
     59     /**
     60      * 测试删除功能
     61      * 
     62      * @throws Exception
     63      */
     64     public void delTest() throws Exception {
     65         // 获取链接
     66         connection = database.getConnection();
     67         // 书写SQL语句
     68         String sql = "delete from test01 where id=?";
     69         // 使用prepareStatement对象进行预编译
     70         statement = connection.prepareStatement(sql);
     71         // 设置参数
     72         statement.setInt(1, 1);
     73         // 获取结果
     74         int result = statement.executeUpdate();
     75 
     76         if (result != 0) {
     77             System.out.println("success");
     78         }
     79     }
     80 
     81     @Test
     82     public void updateTest() throws Exception {
     83         // 获取链接
     84         connection = database.getConnection();
     85         // 书写SQL语句
     86         String sql = "update test01 set name=? where id=?";
     87         // 使用prepareStatement对象进行预编译
     88         statement = connection.prepareStatement(sql);
     89         // 设置参数
     90         statement.setString(1, "admin");
     91         statement.setInt(2, 1);
     92         // 获取结果
     93         int result = statement.executeUpdate();
     94 
     95         if (result != 0) {
     96             System.out.println("success");
     97         }
     98     }
     99 
    100     @Test
    101     /**
    102      * 测试查询全部
    103      * 
    104      * @throws Exception
    105      */
    106     public void selectTest() throws Exception {
    107 
    108         // 创建链接
    109         connection = database.getConnection();
    110         if (connection == null) {// 判断是否获取到了链接
    111             return;
    112         }
    113         // 书写SQL
    114         String sql = "select id,name from test01 where id=?";
    115         // 预编译SQL
    116         statement = connection.prepareStatement(sql);
    117         // 设置参数
    118         statement.setInt(1, 1);
    119         // 获取结果集
    120         result = statement.executeQuery();
    121 
    122         if (result.next()) {
    123             System.out.println("successful");
    124         }
    125         
    126     }
    127 }

      这就是自定义一个简单的JDBC连接池实现方法,希望能给大家一个参考,也希望大家多多支持我。

     

  • 相关阅读:
    stenciljs 学习四 组件装饰器
    stenciljs 学习三 组件生命周期
    stenciljs 学习二 pwa 简单应用开发
    stenciljs ionic 团队开发的方便web 组件框架
    stenciljs 学习一 web 组件开发
    使用npm init快速创建web 应用
    adnanh webhook 框架 hook rule
    adnanh webhook 框架 hook 定义
    adnanh webhook 框架request values 说明
    adnanh webhook 框架execute-command 以及参数传递处理
  • 原文地址:https://www.cnblogs.com/kaikai-2018/p/10420860.html
Copyright © 2011-2022 走看看