JDBC连接池一 自定义连接池
package com.mozq.jdbc; import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; /**
* 使用Properties类,从配置文件获取配置信息。实现JDBCUtils工具类
*
* @author jie
*
*/
public class JDBCUtils_V2 {
// 1.准备配置信息
public static String dirverClass;
public static String url;
public static String user;
public static String password; static {
ClassLoader classLoader = JDBCUtils_V2.class.getClassLoader();
InputStream inStream = classLoader.getResourceAsStream("db.properties");
Properties properties = new Properties();
try {
properties.load(inStream);
dirverClass = properties.getProperty("dirverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password"); Class.forName(dirverClass);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
*
* @throws ClassNotFoundException
*/
public static Connection getConnection() {
// 2.加载驱动,获得链接
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
}catch (SQLException e) {
e.printStackTrace();
}
return connection;
} /**
* 释放资源,注意资源的释放顺序
*/
public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.mozq.jdbc; import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor; /**
* 装饰者设计模式:需要增强接口实现类的接口方法。创建实现接口的一个装饰类。
* 实例:增强Connection实现类的close()方法
* 装饰类的设计步骤:
* 1.实现接口
* 2.提供含有接口类型参数的构造器
* 3.提供接口类型成员变量
* 4.增强需要的方法
* 5.调用接口类型变量,实现不需要增强的方法
* @author jie
*
*/
public class MyConnection implements Connection {
//1.定义接口变量
private Connection conn; private List<Connection> pool; //2.定义接口变量为参数的构造器
public MyConnection(Connection conn , List<Connection> pool){
this.conn = conn;
this.pool = pool;
} //3.增强需要的方法
@Override
public void close() throws SQLException {
pool.add(conn);
System.out.println("将连接放回连接池");
} //4.调用接口变量,实现不需要增强的方法
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public void commit() throws SQLException {
// TODO Auto-generated method stub } @Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub } @Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub } @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub } @Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub } @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
// TODO Auto-generated method stub } @Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
// TODO Auto-generated method stub } @Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub } @Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} }
package com.mozq.jdbc; import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger; import javax.sql.DataSource; public class MyDataSourceMyConn implements DataSource {
// 准备一个池子保存连接
private static LinkedList<Connection> pool = new LinkedList<Connection>(); // 从配置文件加载参数
private static int init = 5; static {
// 初始化池子
for (int i = 0; i < init; ++i) {
Connection connection = JDBCUtils_V2.getConnection(); //增强Connection实现类
MyConnection myConnection = new MyConnection(connection, pool);
pool.add(myConnection);
}
} /**
* 覆盖获取连接的方法
*/
@Override
public Connection getConnection() throws SQLException {
// 获取连接前先判断
if (pool.size() == 0) {
//如果没有连接,创建一些
for (int i = 0; i < init; ++i) {
Connection connection = JDBCUtils_V2.getConnection(); //增强Connection实现类
MyConnection myConnection = new MyConnection(connection, pool);
pool.add(myConnection);
}
}
//从池子里获取连接返回
return pool.remove();
} @Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public Connection getConnection(String username, String password) throws SQLException {
// TODO Auto-generated method stub
return null;
} }
package com.mozq.jdbc.test; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Test; import com.mozq.jdbc.JDBCUtils_V2;
import com.mozq.jdbc.MyDataSourceMyConn; public class MyDataSourceMyConnTest {
@Test
public void insert() {
// 准备参数
String user = "刘备";
String password = "123"; Connection conn = null;
PreparedStatement pstmt = null;
DataSource myDataSource = new MyDataSourceMyConn();
try {
// 获取链接
conn = myDataSource.getConnection();
// 获取语句执行对象
String sql = "insert into t_user (name, password) values(?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user);
pstmt.setString(2, password);
// 结果处理
int row = pstmt.executeUpdate();
if (row > 0) {
System.out.println("插入用户成功");
} else {
System.out.println("插入用户失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils_V2.release(conn, pstmt, null);;
}
}
}
JDBC连接池一 自定义连接池的更多相关文章
- Executors提供的四种线程池和自定义线程池
JAVA并发编程——EXECUTORS 线程池的思想是一种对象池的思想,开放一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理.当有线程任务时,从池中取一个,执行完毕,对象 ...
- JDBC自定义连接池
开发中,"获得连接"和"释放资源"是非常消耗系统资源的,为了解决此类性能问题可以采用连接池技术来共享连接Connection. 1.概述 用池来管理Connec ...
- SpringBoot 自定义线程池
本教程目录: 自定义线程池 配置spring默认的线程池 1. 自定义线程池 1.1 修改application.properties task.pool.corePoolSize=20 task.p ...
- SpringBoot 自定义线程池,多线程
原文:https://www.jianshu.com/p/832f2b162450 我们都知道spring只是为我们简单的处理线程池,每次用到线程总会new 一个新的线程,效率不高,所以我们需要自定义 ...
- JDBC连接池-自定义连接池
JDBC连接池 java JDBC连接中用到Connection 在每次对数据进行增删查改 都要 开启 .关闭 ,在实例开发项目中 ,浪费了很大的资源 ,以下是之前连接JDBC的案例 pack ...
- JDBC连接池原理、自定义连接池代码实现
首先自己实现一个简单的连接池: 数据准备: CREATE DATABASE mybase; USE mybase; CREATE TABLE users( uid INT PRIMARY KEY AU ...
- JDBC数据源连接池(4)---自定义数据源连接池
[续上文<JDBC数据源连接池(3)---Tomcat集成DBCP>] 我们已经 了解了DBCP,C3P0,以及Tomcat内置的数据源连接池,那么,这些数据源连接池是如何实现的呢?为了究 ...
- JavaWeb之数据源连接池(4)---自定义数据源连接池
[续上文<JavaWeb之数据源连接池(3)---Tomcat>] 我们已经 了解了DBCP,C3P0,以及Tomcat内置的数据源连接池,那么,这些数据源连接池是如何实现的呢?为了究其原 ...
- JDBC连接池(三)DBCP连接池
JDBC连接池(三)DBCP连接池 在前面的随笔中提到 了 1.JDBC自定义连接池 2. C3P0连接池 今天将介绍DBCP连接池 第一步要导入jar包 (注意:mysql和mysql 驱动 ...
随机推荐
- UI 自动化测试工具BackstopJS简介(1)
BackstopJS源码地址 https://github.com/garris/BackstopJS 我写了一个DEMO放到github上面,https://github.com/shenggen1 ...
- Android wifi 从连接态自动断开的解决办法(dhcp导致)【转】
本文转载自:http://blog.csdn.net/DKBDKBDKB/article/details/38490201 对wifi部分的代码流程已经看了段时间,前两天终于解决了工作中遇到的一个wi ...
- escape() VS encodeURI() VS encodeURIComponent()
JavaScript中有三个可以对字符串编码的函数,分别是: escape,encodeURI,encodeURIComponent,相应3个解码函数:unescape,decodeURI,decod ...
- 手写Future模式
根据前面我所说的Futrue模式,手写一个: 分别对应的Java代码,大家拿来参考: package FutureTest; //公共data数据接口 public abstract class Da ...
- Android studio 添加assets文件夹
我们知道Eclipse创建的工程默认是有个assets文件夹的,但是Android studio默认没有帮我们创建,那么我们就自己创建一个就好啦. (1)手动创建 在项目的顶部有个下拉,默认选择的是A ...
- innerText和innerHTML
起因 由于公司的项目以前不考虑浏览器的兼容性问题,当时只考虑ie8浏览器,封装的控件也只针对ie8,我后面的做的时候,也就针对ie8,最近发现,封装的日期控件,在firefox竟然没法显示出来,去看J ...
- 从Inception v1,v2,v3,v4,RexNeXt到Xception再到MobileNets,ShuffleNet,MobileNetV2
from:https://blog.csdn.net/qq_14845119/article/details/73648100 Inception v1的网络,主要提出了Inceptionmodule ...
- all.css
@charset "utf-8"*{-webkit-tap-highlight-color:rgba(0,0,0,0); padding:0; margin:0;}body{ fo ...
- 小工具之Synergy
用于两个主机共享键盘和鼠标的工具: 软件名字:synergy软件主页: http://synergy-foss.org支持平台:linux,mac,windows 通吃 作用:通过网络在多台主机之间共 ...
- AngularJS系统学习之$watch(监控)
在scope的内置的所有函数中,用的最多的可能就是$watch函数了, 当你的数据模型中某一部分发生变化时,$watch函数可以向你发出通知. 你可以监控单个对象的属性,亦可以监控需要经过计算的结果( ...