JDBC自定义连接池过程详解
作者:海之浪子 发布时间:2023-11-17 13:27:55
标签:JDBC,连接,池
这篇文章主要介绍了JDBC自定义连接池过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
开发中,"获得连接"和"释放资源"是非常消耗系统资源的,为了解决此类性能问题可以采用连接池技术来共享连接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);
}
}
来源:https://www.cnblogs.com/haizhilangzi/p/10909089.html


猜你喜欢
- 在 C# 以二进制形式读取数据时使用的是 BinaryReader 类。BinaryReader 类中提供的构造方法有 3 种,具体的语法形
- 霓虹是用来描绘图像的轮廓,勾画出颜色变化的边缘,加强其过度效果,使图像产生轮廓发光的效果。主要步骤:1、根据当前像素与其右方和下方像素的梯度
- Android ListView的优化,在做Android项目的时候,在用到ListView 界面及数据显示,这个时候如果资源过大,对项目来
- 使用applicationContext.xml配置文件SpringBoot默认是通过Java代码进行依赖注入,但也为xml形式的依赖注入提
- 介绍Dubbo 是一款高性能、轻量级的 Java RPC 框架,由阿里巴巴开源并贡献至 Apache 基金会。它能够提供服务的注册与发现、负
- IISExpress 配置允许外部访问详细介绍1.找到IISExpress的配置文件,位于 <文档>/IISExpr
- 在实际项目开发过程中,我们经常需要对某个对象或者某个集合中的元素进行排序,常用的两种方式是实现某个接口。常见的可以实现比较功能的接口有Com
- 前言最近在逛博客的时候看到了有关Redis方面的面试题,其中提到了Redis在内存达到最大限制的时候会使用LRU等淘汰机制,然后找了这方面的
- 路径分隔符:Windows下是“\”unix|linux下是“/”考虑到程序的可移植性,创建文件时建议大家选用"/",因
- 一、图示我们先来看看今天要介绍哪些内存溢出案例,这里总结了一张图,如下所示。二、定义主类结构首先,我们创建一个名称为BlowUpJVM的类,
- C# 中闭包(Closure)详解这个问题是在最近一次英格兰 Brighton ALT.NET Beers 活动中提出来的。我发现,如果不用
- 本文实例为大家分享了使用C#写一个时钟,供大家参考,具体内容如下时钟是这样的一共使用四个控件即可:WinFrom窗体应用程序代码:using
- 效果图接下来就是一波贴代码的过程自定义Dialogpublic class SinaSendView extends Dialog { &n
- 最开始接触到相关的内容应该是从volatile关键字开始的吧,知道它可以保证变量的可见性,而且利用它可以实现读与写的原子操作。。。但是要实现
- import java.io.ByteArrayOutputStream;import java.io.InputStream;//从输入流
- 这两天看到Hibernate的代理部分,第一反应是底层使用了反射,针对用户实体生成了代理类,后来反应过来了,反射没有任何可以产生新类的能力,
- 线程组构造方法我们看这个线程组,线程组名字是system,设置优先级,然后指定父线程是空,可以看出这个是根线程组,这个方法是私有的,不是给我
- 先看看效果图:package com.fenghuo.struts.download;import java.net.URLEncoder;
- eclipse中改变默然的workspace的方法可以有以下几种:1.在创建project的时候,手动选择使用新的workspace,如创建
- 前言在我们的项目中,通常会把数据存储到关系型数据库中,比如Oracle,SQL Server,Mysql等,但是关系型数据库对于并发的支持并