当前位置:网站首页>Connection pool - return connection details (Part 1)
Connection pool - return connection details (Part 1)
2022-07-27 20:09:00 【Soup key】
Catalog
How to return the database connection
The idea of returning database connection by inheritance
The implementation steps of returning database connection by inheritance
There are some problems in the way of inheritance
Decoration design pattern returns the idea of database connection
Decoration design pattern database connection implementation steps
The decorative design pattern returns the problem of database connection
Decoration design pattern return example demonstration
How to return the database connection
- Inheritance mode
- Decoration design mode
- adapter design pattern
- Dynamic agent mode
The idea of returning database connection by inheritance
- Connect objects by printing , Find out DriverManager The obtained connection implementation class is JDBC4Connection
- Then we can customize a class , Inherit JDBC4Connection This class , rewrite close() Method , Complete the return of the connection object
The implementation steps of returning database connection by inheritance
- 1. Define a class , Inherit JDBC4Connection
- 2. Definition Connection Member variables for connection objects and connection pool container objects
- 3. Through the parametric construction method to complete the assignment of member variables
- 4. rewrite close Method , Add the connection object to the pool
There are some problems in the way of inheritance
- By looking at JDBC Method discovery of tool class getting connection
- Although we customize a subclass , Finished returning the connection
- however DriverManager What we got was JDBC4Connection This object , It's not our subclass object
- And we can't modify the function of the class in the driver package as a whole , So inherit this way It won't work
Decoration design pattern returns the idea of database connection
- We can customize a class , Realization Connection Interface
- In this way, we have and JDBC4Connection The same behavior
- rewrite close() Method , Complete the return of the connection
- The rest of the functions call mysql The driver package implements the original method of the class
Decoration design pattern database connection implementation steps
- 1. Define a class , Realization Connection Interface
- 2. Definition Connection Member variables for connection objects and connection pool container objects
- 3. Through the parametric construction method to complete the assignment of member variables
- 4. rewrite close() Method , Add the connection object to the pool
- 5. The remaining method , Just call mysql The connection object of the driver package is completed
- 6. In a custom connection pool , The obtained connection object is packaged by a custom connection object
The decorative design pattern returns the problem of database connection
- Realization Connection After the interface
- There are a lot of methods that need to be overridden in custom classes
Decoration design pattern return example demonstration

package demo02.myDataSourse; import java.sql.*; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; //1. Define a class , Realization Connection Interface public class demomyConnection implements Connection { //2. Define the member variables of the connection object and the connection pool container object private Connection con; private List<Connection> pool; //3. Assign a value to the member variable through the parametric construction method public demomyConnection(Connection con, List<Connection> pool) { this.con = con; this.pool = pool; } //4. rewrite close Method , Complete the return connection @Override public void close() throws SQLException { pool.add(con); } //5. The remaining method , Or call the functions in the original connection object @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<String, Class<?>> getTypeMap() throws SQLException { return con.getTypeMap(); } @Override public void setTypeMap(Map<String, Class<?>> 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> T unwrap(Class<T> iface) throws SQLException { return con.unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return con.isWrapperFor(iface); } }
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; // Custom database connection pool public class demoDataSourse implements DataSource{ //1. Preparation container , Used to save multiple connection objects private static List<Connection> pool = Collections.synchronizedList(new ArrayList<>()); //2. Define static code blocks , Get... Through the tool class 10 A connection object static{ for(int i=1;i<=10;i++){ Connection con = JDBCUtils.getConnection(); pool.add(con); } } //3. rewrite getConnection(), Used to get a connection object @Override public Connection getConnection() throws SQLException { if(pool.size()>0){ Connection con = pool.remove(0); // Through the customized connection object , Wrap the original connection object demomyConnection mycon = new demomyConnection(con,pool); return mycon; }else{ throw new RuntimeException(" The number of connections has been exhausted "); } } //4. Definition getSize Method , Gets the size of the connection pool container public int getSize(){ return pool.size(); } @Override public Connection getConnection(String username, String password) throws SQLException { return null; } @Override public <T> T unwrap(Class<T> 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; } }
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. Create connection pool object demoDataSourse dataSourse = new demoDataSourse(); System.out.println(" Quantity before use " + dataSourse.getSize()); //2. Get the connection object through the connection pool object Connection con = dataSourse.getConnection(); //3. Query all the information in the student table String sql = "SELECT * FROM student"; PreparedStatement pst = con.prepareStatement(sql); //4. perform sql sentence , Receive the result set ResultSet rs = pst.executeQuery(); //5. Processing result set while(rs.next()){ System.out.println(rs.getInt("sid")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getDate("birthday")); } //6. Release resources rs.close(); pst.close(); con.close();// After use , Return System.out.println(" Quantity after use " + dataSourse.getSize()); } }
边栏推荐
- C#网络应用编程,实验一:WPF练习
- #yy关于鱼的英文学习
- Leetcode exercise 2 - sum of two numbers
- Overview of deep active learning 2020
- China business CDP white paper | love Analysis Report
- Basic functions of pytorch tensor
- [C # network application programming] Experiment 3: process management exercise
- Online judge output overrun
- C#网络应用编程,实验2:IP地址转换和域名解析练习
- 剑指 Offer 25. 合并两个排序的链表
猜你喜欢

Unity2d dynamic cartoon script (animation demonstration II for the chapter of Tiger Bridge)

Online Judge 输出超限

ms721负载测试

Underlying principle of mvcc

Understanding of basic concepts of channel capacity and channel bandwidth

mysql数据库中的数据如何加密呢?mysql8.0自带新特性

System information function of MySQL function summary

Talk about how redis handles requests

Detailed introduction to common coordinate system of cesium

TS2532: Object is possibly ‘undefined‘
随机推荐
探索新一代活动获客方式,虚拟化活动棋胜一招 | 厂商征集
[论文阅读] Rich Feature Hierarchies for Accurate Object Detection and Semantic Segmentation
内置函数时间日期函数
Cesium常用坐标系详细介绍
Unity2d dynamic cartoon script (animation demonstration II for the chapter of Tiger Bridge)
由单片机XTALIN引脚和XTALOUT引脚导出的对晶体震荡电路的深入理解
TS2532: Object is possibly ‘undefined‘
How to encrypt the data in MySQL database? Mysql8.0 comes with new features
Talk about how redis handles requests
内置函数其它函数
Underlying principle of mvcc
剑指 Offer 25. 合并两个排序的链表
PKI/TLS 工具之CFSSL —— 筑梦之路
China business CDP white paper | love Analysis Report
uva1377
1.2、基于增量式生成遮挡与对抗抑制的行人再识别(代码理解与实验进度+报告)
C# 后台GC 的前因后果
‘vite‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件
总线Bus是什么意思
focal loss


