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连接池一 自定义连接池的更多相关文章

  1. Executors提供的四种线程池和自定义线程池

    JAVA并发编程——EXECUTORS 线程池的思想是一种对象池的思想,开放一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理.当有线程任务时,从池中取一个,执行完毕,对象 ...

  2. JDBC自定义连接池

    开发中,"获得连接"和"释放资源"是非常消耗系统资源的,为了解决此类性能问题可以采用连接池技术来共享连接Connection. 1.概述 用池来管理Connec ...

  3. SpringBoot 自定义线程池

    本教程目录: 自定义线程池 配置spring默认的线程池 1. 自定义线程池 1.1 修改application.properties task.pool.corePoolSize=20 task.p ...

  4. SpringBoot 自定义线程池,多线程

    原文:https://www.jianshu.com/p/832f2b162450 我们都知道spring只是为我们简单的处理线程池,每次用到线程总会new 一个新的线程,效率不高,所以我们需要自定义 ...

  5. JDBC连接池-自定义连接池

    JDBC连接池 java JDBC连接中用到Connection   在每次对数据进行增删查改 都要 开启  .关闭  ,在实例开发项目中 ,浪费了很大的资源 ,以下是之前连接JDBC的案例 pack ...

  6. JDBC连接池原理、自定义连接池代码实现

    首先自己实现一个简单的连接池: 数据准备: CREATE DATABASE mybase; USE mybase; CREATE TABLE users( uid INT PRIMARY KEY AU ...

  7. JDBC数据源连接池(4)---自定义数据源连接池

    [续上文<JDBC数据源连接池(3)---Tomcat集成DBCP>] 我们已经 了解了DBCP,C3P0,以及Tomcat内置的数据源连接池,那么,这些数据源连接池是如何实现的呢?为了究 ...

  8. JavaWeb之数据源连接池(4)---自定义数据源连接池

    [续上文<JavaWeb之数据源连接池(3)---Tomcat>] 我们已经 了解了DBCP,C3P0,以及Tomcat内置的数据源连接池,那么,这些数据源连接池是如何实现的呢?为了究其原 ...

  9. JDBC连接池(三)DBCP连接池

    JDBC连接池(三)DBCP连接池 在前面的随笔中提到 了  1.JDBC自定义连接池  2. C3P0连接池 今天将介绍DBCP连接池 第一步要导入jar包   (注意:mysql和mysql 驱动 ...

随机推荐

  1. How to deploy a Delphi OSX project from the command line

    Delphi has a well developed command line build process (via MSBuild) for Windows projects. After the ...

  2. Javascript学习之Date对象详解

    1.定义 创建 Date 实例用来处理日期和时间.Date 对象基于1970年1月1日世界协调时起的毫秒数 2.语法 构造函数 new Date() new Date(value) value代表自世 ...

  3. 关于4Ps 、4Cs 、4Rs 、4Vs营销策略的内容及优劣比较

  4. 对私有API提交的注意事项

    1.这个等于堵死了调试断点.关闭就不能断点调试了. 2.对于敏感的函数名要做一个对称加密处理. 防止二进制文件的静态扫描. 3.对于调用私有函数的方法,可以做一个宏定义包装. #define 你的正常 ...

  5. jmeter中的响应断言

    断言就类似LoadRunner中的检查点.对上一个请求返回的信息,做字符串.数据包大小.HTML.XML.图片等做判断,确保返回的信息的准确性. jmeter的断言有好多,下面是一个响应断言 新建一个 ...

  6. jQuery ajax序列化函数

    参数序列化$.param() 举例: <!DOCTYPE html> <html> <head> <script src="https://ajax ...

  7. 大数相乘(hdu 1402)

    ------------------题目链接--------------------- 题目没啥说的,两个数相乘,fft,一发模板就AC,kuangbin模板大法好,不懂原理的小白也能体验AC. 个人 ...

  8. 理解 Android Fragment

    /***************************************************************************************** * 理解 Andr ...

  9. Java笔记(十)

    正则表达式: 符合一定规则的表达式,用于专门操作字符串. 对QQ号码进行校验,要求:5-11位,0不能开头,只能是数字. public class Demo{ public static void m ...

  10. js 判断滚动条是不是在浏览器底部

    http://jingyan.baidu.com/album/86f4a73e91da7837d65269d5.html?picindex=2