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 驱动 ...
随机推荐
- Java其实不支持垃圾回收
Java其实不支持垃圾回收.如果真的支持的话,大多数Java程序在运行的一开始就应该把程序本身删除,因为这些程序本身就是垃圾. // TODO: This is a 分割线. Please no ...
- Mac端博客发布工具推荐
引子 推荐一款好用的 Mac 端博客发布工具. 下载地址 echo 博客对接 这里以cnblog为例.接入类型为metawebblog,access point可以在cnblog的设置最下边找到,然后 ...
- 怎样使用alsa API
翻译文章的链接: http://equalarea.com/paul/alsa-audio.html 关于怎么使用ALSA API教程 这份文档帮助对ALSA API使用入门.不是一个完整的ALSA ...
- Bestcoder round 18----B题(一元三次方程确定区间的最大值(包含极值比较))
Math Problem Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Tota ...
- hadoop运行测试命令遇到的问题
2017-02-16 09:46:14,926 INFO mapreduce.Job: Task Id : attempt_1487148856575_0001_m_000001_0, Status ...
- codeforces B. Ilya and Queries 解题报告
题目链接:http://codeforces.com/problemset/problem/313/B 题目意思:给出一个只有 "." 和 "#" 组成的序 ...
- dancing link 精确覆盖 重复覆盖 (DLX)
申明:因为转载的没有给出转载链接,我就把他的链接附上,请尊重原创: http://www.cnblogs.com/-sunshine/p/3358922.html 如果谁知道原创链接 给一下,请尊重原 ...
- 2016.4.23浙江省赛(zoj3936 zoj3938 zoj3940 zoj3944 zoj3946 zoj3947 )
A Apples and Ideas Time Limit: 2 Seconds Memory Limit: 65536 KB "If you have an apple ...
- (测试)LaTeX公式
\[a^2+b^2=c^2\] \[F(\omega)=\mathcal{F}[f(t)]=\int_{-\infty}^\infty f(t)e^{-iwt}\,dt\] \[\sum_{i=0}^ ...
- POJ3261(后缀数组+2分枚举)
Milk Patterns Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 12972 Accepted: 5769 Ca ...