连接池-归还连接详解(上)

  • 目录

    归还数据库连接的方式

    继承方式归还数据库连接的思想

    继承方式归还数据库连接的实现步骤

    继承方式归还数据库连接存在的问题

    装饰设计模式归还数据库连接的思想

    装饰设计模式归还数据库连接的实现步骤

    装饰设计模式归还数据库连接存在的问题

    装饰设计模式归还实例演示


  • 归还数据库连接的方式

  • 继承方式
  • 装饰设计模式
  • 适配器设计模式
  • 动态代理方式
  • 继承方式归还数据库连接的思想

  • 通过打印连接对象,发现DriverManager获取的连接实现类是JDBC4Connection
  • 那我们就可以自定义一个类,继承JDBC4Connection这个类,重写close()方法,完成连接对象的归还
  • 继承方式归还数据库连接的实现步骤

  • 1.定义一个类,继承JDBC4Connection
  • 2.定义Connection连接对象和连接池容器对象的成员变量
  • 3.通过有参构造方法完成对成员变量的赋值
  • 4.重写close方法,将连接对象添加到池中
  • 继承方式归还数据库连接存在的问题

  • 通过查看JDBC工具类获取连接的方法发现
  • 我们虽然自定义了一个子类,完成了归还连接操作
  • 但是DriverManager获取的还是JDBC4Connection这个对象,并不是我们的子类对象
  • 而我们又不能整体去修改驱动包中类的功能,所以继承这种方式行不通
  • 装饰设计模式归还数据库连接的思想

  • 我们可以自定义一个类,实现Connection接口
  • 这样就具备了和JDBC4Connection相同的行为了
  • 重写close()方法,完成连接的归还
  • 其余的功能还调用mysql驱动包实现类原有的方法即可
  • 装饰设计模式归还数据库连接的实现步骤

  • 1.定义一个类,实现Connection接口
  • 2.定义Connection连接对象和连接池容器对象的成员变量
  • 3.通过有参构造方法完成对成员变量的赋值
  • 4.重写close()方法,将连接对象添加到池中
  • 5.剩余方法,只需要调用mysql驱动包的连接对象完成即可
  • 6.在自定义连接池中,将获取的连接对象通过自定义连接对象进行包装
  • 装饰设计模式归还数据库连接存在的问题

  • 实现Connection接口后
  • 有大量的方法需要在自定义类中重写
  • 装饰设计模式归还实例演示

  • 连接池-归还连接详解(上)_第1张图片
  • package demo02.myDataSourse;
    
    import java.sql.*;
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    import java.util.concurrent.Executor;
        //1.定义一个类,实现Connection接口
    public class demomyConnection implements Connection {
        //2.定义连接对象和连接池容器对象的成员变量
        private Connection con;
        private List pool;
        //3.通过有参构造方法为成员变量赋值
        public demomyConnection(Connection con, List pool) {
            this.con = con;
            this.pool = pool;
        }
        //4.重写close方法,完成归还连接
        @Override
        public void close() throws SQLException {
            pool.add(con);
        }
        //5.剩余方法,还是调用原有的连接对象中的功能即可
        @Override
        public Statement createStatement() throws SQLException {
            return con.createStatement();
        }
    
        @Override
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            return con.prepareStatement(sql);
        }
    
        @Override
        public CallableStatement prepareCall(String sql) throws SQLException {
            return con.prepareCall(sql);
        }
    
        @Override
        public String nativeSQL(String sql) throws SQLException {
            return con.nativeSQL(sql);
        }
    
        @Override
        public void setAutoCommit(boolean autoCommit) throws SQLException {
            con.setAutoCommit(autoCommit);
        }
    
        @Override
        public boolean getAutoCommit() throws SQLException {
            return con.getAutoCommit();
        }
    
        @Override
        public void commit() throws SQLException {
            con.commit();
        }
    
        @Override
        public void rollback() throws SQLException {
            con.rollback();
        }
    
        @Override
        public boolean isClosed() throws SQLException {
            return con.isClosed();
        }
    
        @Override
        public DatabaseMetaData getMetaData() throws SQLException {
            return con.getMetaData();
        }
    
        @Override
        public void setReadOnly(boolean readOnly) throws SQLException {
            con.setReadOnly(readOnly);
        }
    
        @Override
        public boolean isReadOnly() throws SQLException {
            return con.isReadOnly();
        }
    
        @Override
        public void setCatalog(String catalog) throws SQLException {
            con.setCatalog(catalog);
        }
    
        @Override
        public String getCatalog() throws SQLException {
            return con.getCatalog();
        }
    
        @Override
        public void setTransactionIsolation(int level) throws SQLException {
            con.setTransactionIsolation(level);
        }
    
        @Override
        public int getTransactionIsolation() throws SQLException {
            return con.getTransactionIsolation();
        }
    
        @Override
        public SQLWarning getWarnings() throws SQLException {
            return con.getWarnings();
        }
    
        @Override
        public void clearWarnings() throws SQLException {
            con.clearWarnings();
        }
    
        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
            return con.createStatement(resultSetType,resultSetConcurrency);
        }
    
        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return con.prepareStatement(sql,resultSetType,resultSetConcurrency);
        }
    
        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return con.prepareCall(sql,resultSetType,resultSetConcurrency);
        }
    
        @Override
        public Map> getTypeMap() throws SQLException {
            return con.getTypeMap();
        }
    
        @Override
        public void setTypeMap(Map> map) throws SQLException {
            con.setTypeMap(map);
        }
    
        @Override
        public void setHoldability(int holdability) throws SQLException {
            con.setHoldability(holdability);
        }
    
        @Override
        public int getHoldability() throws SQLException {
            return con.getHoldability();
        }
    
        @Override
        public Savepoint setSavepoint() throws SQLException {
            return con.setSavepoint();
        }
    
        @Override
        public Savepoint setSavepoint(String name) throws SQLException {
            return con.setSavepoint(name);
        }
    
        @Override
        public void rollback(Savepoint savepoint) throws SQLException {
            con.rollback(savepoint);
        }
    
        @Override
        public void releaseSavepoint(Savepoint savepoint) throws SQLException {
            con.releaseSavepoint(savepoint);
        }
    
        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return con.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
        }
    
        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return con.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
        }
    
        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return con.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
        }
    
        @Override
        public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
            return con.prepareStatement(sql,autoGeneratedKeys);
        }
    
        @Override
        public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
            return con.prepareStatement(sql,columnIndexes);
        }
    
        @Override
        public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
            return con.prepareStatement(sql,columnNames);
        }
    
        @Override
        public Clob createClob() throws SQLException {
            return con.createClob();
        }
    
        @Override
        public Blob createBlob() throws SQLException {
            return con.createBlob();
        }
    
        @Override
        public NClob createNClob() throws SQLException {
            return con.createNClob();
        }
    
        @Override
        public SQLXML createSQLXML() throws SQLException {
            return con.createSQLXML();
        }
    
        @Override
        public boolean isValid(int timeout) throws SQLException {
            return con.isValid(timeout);
        }
    
        @Override
        public void setClientInfo(String name, String value) throws SQLClientInfoException {
            con.setClientInfo(name,value);
        }
    
        @Override
        public void setClientInfo(Properties properties) throws SQLClientInfoException {
            con.setClientInfo(properties);
        }
    
        @Override
        public String getClientInfo(String name) throws SQLException {
            return con.getClientInfo(name);
        }
    
        @Override
        public Properties getClientInfo() throws SQLException {
            return con.getClientInfo();
        }
    
        @Override
        public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
            return con.createArrayOf(typeName,elements);
        }
    
        @Override
        public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
            return con.createStruct(typeName,attributes);
        }
    
        @Override
        public void setSchema(String schema) throws SQLException {
            con.setSchema(schema);
        }
    
        @Override
        public String getSchema() throws SQLException {
            return con.getSchema();
        }
    
        @Override
        public void abort(Executor executor) throws SQLException {
            con.abort(executor);
        }
    
        @Override
        public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
            con.setNetworkTimeout(executor,milliseconds);
        }
    
        @Override
        public int getNetworkTimeout() throws SQLException {
            return con.getNetworkTimeout();
        }
    
        @Override
        public  T unwrap(Class iface) throws SQLException {
            return con.unwrap(iface);
        }
    
        @Override
        public boolean isWrapperFor(Class iface) throws SQLException {
            return con.isWrapperFor(iface);
        }
    }
  • 连接池-归还连接详解(上)_第2张图片
  • package demo02.myDataSourse;
    import demo02.utils.JDBCUtils;
    
    import javax.sql.DataSource;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.SQLFeatureNotSupportedException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.logging.Logger;
    
    //自定义数据库连接池
    public class demoDataSourse implements DataSource{
        //1.准备容器,用于保存多个连接对象
        private static List pool = Collections.synchronizedList(new ArrayList<>());
        //2.定义静态代码块,通过工具类获取10个连接对象
        static{
            for(int i=1;i<=10;i++){
                Connection con = JDBCUtils.getConnection();
                pool.add(con);
            }
        }
        //3.重写getConnection(),用于获取一个连接对象
        @Override
        public Connection getConnection() throws SQLException {
            if(pool.size()>0){
                Connection con = pool.remove(0);
                //通过自定义的连接对象,对原有的连接对象进行包装
                demomyConnection mycon = new demomyConnection(con,pool);
                return mycon;
            }else{
                throw new RuntimeException("连接数量已用尽");
            }
        }
        //4.定义getSize方法,获取连接池容器的大小
        public int getSize(){
            return pool.size();
        }
        @Override
        public Connection getConnection(String username, String password) throws SQLException {
            return null;
        }
    
        @Override
        public  T unwrap(Class iface) throws SQLException {
            return null;
        }
    
        @Override
        public boolean isWrapperFor(Class iface) throws SQLException {
            return false;
        }
    
        @Override
        public PrintWriter getLogWriter() throws SQLException {
            return null;
        }
    
        @Override
        public void setLogWriter(PrintWriter out) throws SQLException {
    
        }
    
        @Override
        public void setLoginTimeout(int seconds) throws SQLException {
    
        }
    
        @Override
        public int getLoginTimeout() throws SQLException {
            return 0;
        }
    
        @Override
        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
            return null;
        }
    }
  • 连接池-归还连接详解(上)_第3张图片
  • package demo02.myDataSourse;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    public class demoDataSourseTest {
        public static void main(String[] args) throws Exception {
            //1.创建连接池对象
            demoDataSourse dataSourse = new demoDataSourse();
    
            System.out.println("使用之前的数量" + dataSourse.getSize());
    
            //2.通过连接池对象获取连接对象
            Connection con = dataSourse.getConnection();
            //3.查询学生表的全部信息
            String sql = "SELECT * FROM student";
            PreparedStatement pst = con.prepareStatement(sql);
            //4.执行sql语句,接收结果集
            ResultSet rs = pst.executeQuery();
            //5.处理结果集
            while(rs.next()){
                System.out.println(rs.getInt("sid")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getDate("birthday"));
            }
            //6.释放资源
            rs.close();
            pst.close();
            con.close();//用完以后,进行归还
    
            System.out.println("使用之后的数量" + dataSourse.getSize());
        }
    }

你可能感兴趣的:(JDBC,java,开发语言,数据库)