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

1、概述

用池来管理Connection,这样可以重复使用Connection.这样我们就不用创建Connection,用池来管理Connection对象,当使用完Connection对象后,将Connection对象归还给池,这样后续还可以从池中获取Connection对象,可以重新再利用这个连接对象啦。

java为数据库连接池提供了公共接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。

常见的连接池:DBCP,C3P0

2、自定义连接池

编写自定义连接池

1、创建连接池并实现接口javax.sql.DataSource,并使用接口中的getConnection()方法

2、提供一个集合,用于存放连接,可以采用LinkedList

3、后面程序如果需要,可以调用实现类getConnection(),并从list中获取链接。为保证当前连接只能提供给一个线程使用,所以我们需要将连接先从连接池中移除

4、当用户用完连接后,将连接归还到连接池中

3、自定义连接池采用装饰者设计模式

public class ConnectionPool implements Connection {

    private Connection connection;
private LinkedList<Connection> pool; public ConnectionPool(Connection connection, LinkedList<Connection> pool){
this.connection=connection;
this.pool=pool;
} @Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return connection.prepareStatement(sql);
} @Override
public void close() throws SQLException {
pool.add(connection); }
@Override
public Statement createStatement() throws SQLException {
return null;
} @Override
public CallableStatement prepareCall(String sql) throws SQLException {
return null;
} @Override
public String nativeSQL(String sql) throws SQLException {
return null;
} @Override
public void setAutoCommit(boolean autoCommit) throws SQLException { } @Override
public boolean getAutoCommit() throws SQLException {
return false;
} @Override
public void commit() throws SQLException { } @Override
public void rollback() throws SQLException { } @Override
public boolean isClosed() throws SQLException {
return false;
} @Override
public DatabaseMetaData getMetaData() throws SQLException {
return null;
} @Override
public void setReadOnly(boolean readOnly) throws SQLException { } @Override
public boolean isReadOnly() throws SQLException {
return false;
} @Override
public void setCatalog(String catalog) throws SQLException { } @Override
public String getCatalog() throws SQLException {
return null;
} @Override
public void setTransactionIsolation(int level) throws SQLException { } @Override
public int getTransactionIsolation() throws SQLException {
return 0;
} @Override
public SQLWarning getWarnings() throws SQLException {
return null;
} @Override
public void clearWarnings() throws SQLException { } @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
} @Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
} @Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException { } @Override
public void setHoldability(int holdability) throws SQLException { } @Override
public int getHoldability() throws SQLException {
return 0;
} @Override
public Savepoint setSavepoint() throws SQLException {
return null;
} @Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
} @Override
public void rollback(Savepoint savepoint) throws SQLException { } @Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException { } @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
} @Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
} @Override
public Clob createClob() throws SQLException {
return null;
} @Override
public Blob createBlob() throws SQLException {
return null;
} @Override
public NClob createNClob() throws SQLException {
return null;
} @Override
public SQLXML createSQLXML() throws SQLException {
return null;
} @Override
public boolean isValid(int timeout) throws SQLException {
return false;
} @Override
public void setClientInfo(String name, String value) throws SQLClientInfoException { } @Override
public void setClientInfo(Properties properties) throws SQLClientInfoException { } @Override
public String getClientInfo(String name) throws SQLException {
return null;
} @Override
public Properties getClientInfo() throws SQLException {
return null;
} @Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
} @Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
} @Override
public void setSchema(String schema) throws SQLException { } @Override
public String getSchema() throws SQLException {
return null;
} @Override
public void abort(Executor executor) throws SQLException { } @Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { } @Override
public int getNetworkTimeout() throws SQLException {
return 0;
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}

DataSourcePool

public class DataSourcePool implements DataSource {
//1.创建1个容器用于存储Connection对象
private static LinkedList<Connection> pool = new LinkedList<Connection>(); //2.创建5个连接放到容器中去
static{
for (int i = 0; i < 5; i++) {
Connection conn = JDBCUtils.getConnection();
//放入池子中connection对象已经经过改造了
ConnectionPool connectionPool = new ConnectionPool(conn, pool);
pool.add(connectionPool);
}
} /**
* 重写获取连接的方法
*/
@Override
public Connection getConnection() throws SQLException {
Connection conn = null;
//3.使用前先判断
if(pool.size()==0){
//4.池子里面没有,我们再创建一些
for (int i = 0; i < 5; i++) {
conn = JDBCUtils.getConnection();
//放入池子中connection对象已经经过改造了
ConnectionPool connectionPool = new ConnectionPool(conn, pool);
pool.add(connectionPool);
}
}
//5.从池子里面获取一个连接对象Connection
conn = pool.remove(0);
return conn;
} @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;
}
}

测试代码如下

 @Test
public void test1(){
Connection conn = null;
PreparedStatement pstmt = null;
// 1.创建自定义连接池对象
DataSource dataSource = new DataSourcePool();
try {
// 2.从池子中获取连接
conn = dataSource.getConnection();
String sql = "insert into USER values(?,?)";
//3.必须在自定义的connection类中重写prepareStatement(sql)方法
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "李四");
pstmt.setString(2, "1234");
int rows = pstmt.executeUpdate();
System.out.println("rows:"+rows);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.relase(conn, pstmt, null);
}
}

JDBC自定义连接池的更多相关文章

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

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

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

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

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

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

  4. java自定义连接池

    1.java自定义连接池 1.1连接池的概念: 实际开发中"获取连接"或“释放资源”是非常消耗系统资源的两个过程,为了姐姐此类性能问题,通常情况我们采用连接池技术来贡献连接Conn ...

  5. JDBC 和连接池

    1 JDBC概述 Java DataBase Connectivity,Java数据库连接,一种执行SQL的Java API,为多种关系数据库提供统一访问规范,由一组Java语言编写的类和接口组成.数 ...

  6. day18(JDBC事务&连接池介绍&DBUtils工具介绍&BaseServlet作用)

    day18总结 今日思维导图: 今日内容 事务 连接池 ThreadLocal BaseServlet自定义Servlet父类(只要求会用,不要求会写) DBUtils à commons-dbuti ...

  7. MySQL学习(六)——自定义连接池

    1.连接池概念 用池来管理Connection,这样可以重复使用Connection.有了池,我们就不用自己来创建Connection,而是通过池来获取Connection对象.当使用完Connect ...

  8. 自定义连接池DataSourse

    自定义连接池DataSourse 连接池概述: 管理数据库的连接, 作用: 提高项目的性能.就是在连接池初始化的时候存入一定数量的连接,用的时候通过方法获取,不用的时候归还连接即可.所有的连接池必须实 ...

  9. c3p0、dbcp、tomcat jdbc pool 连接池配置简介及常用数据库的driverClass和驱动包

    [-] DBCP连接池配置 dbcp jar包 c3p0连接池配置 c3p0 jar包 jdbc-pool连接池配置 jdbc-pool jar包 常用数据库的driverClass和jdbcUrl ...

随机推荐

  1. MySQL插入SQL语句后在phpmyadmin中注释显示乱码

    自己写一个建一个简单的数据表,中间加了个注释,但是用PHPmyadmin打开后发现注释不对. 就先查询了一下sql 语句 发现SQL 语句并没有问题,感觉像是显示编码的问题,就先用set names ...

  2. 二. python函数与模块

    第四章.内置函数与装饰器详解 1.内置函数补充1 注:红色圆圈:必会:  紫红色方框:熟练:   绿色:了解 callable() 判断函数是否可以被调用执行 def f1(): pass f1() ...

  3. 【Java_基础】cmd下使用java命令运行class文件提示“错误:找不到或无法加载主类“的问题分析

    1.问题如下 当在命令行使用java命令执行字节码文件时提示“错误:找不到或无法加载主类” 2. 问题分析 这是由于在运行时类的全名应该是包名+类名,例如在包net.xsoftlab.baike下的类 ...

  4. Python9-递归函数-day17

    # 计算方法:人脑复杂,计算机简单#查找:找数据#排序#最短路径#我们学习的算法都是过去时#要了解基础的算法,才能创造出更好的算法#不是所有的事情都能套用现成的方法解决的# 有些时候会用到学过的算法只 ...

  5. CSS里总算是有了一种简单的垂直居中布局的方法了

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  6. 二丶人生苦短,我用python【第二篇】

    1 编码 python解释器在加载 .py 文件中的代码时,对内容默认进行ascill编码,因此存在中文会报错,所以需要告诉python解释器,用什么编码来执行源代码.) ASCII码,主要用于显示现 ...

  7. Java异常架构图及面试题---https://www.cnblogs.com/gaoweixiao99/p/4905860.html

    https://www.cnblogs.com/gaoweixiao99/p/4905860.html 红色为检查异常,就是eclipse要提示你是try catch 还是throws. 非检查异常, ...

  8. Leetcode 365.水壶问题

    水壶问题 有两个容量分别为 x升和 y升的水壶以及无限多的水.请判断能否通过使用这两个水壶,从而可以得到恰好 z升的水? 如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水. 你允许: 装满 ...

  9. LINQ-查询表达式基础

    一.LINQ查询的数据源 从应用程序的角度来看,原始源数据的特定类型和结构并不重要. 应用程序始终将源数据视为 IEnumerable<T> 或 IQueryable<T> 集 ...

  10. 信息安全试验-DES加密!

    信息安全试验二--DES加密算法 本渣表示没有理解原理,照着书上敲了一发,运行无误! 吐槽:手动S盒简直丧心病狂,扩展置换表全是手动输入,加密原理还是很好理解,两次异或,先混淆. 此代码数据由老师给出 ...