上篇简单介绍了jdbc链接数据库;

本篇就说一下自定义连接池以及增删改查的测试:

自定义连接池

自定义链接池的原因

    JDBC连接中用到Connection   在每次对数据进行增删查改 都要 开启  、关闭  ,在开发项目中 ,浪费了很大的资源 ,所以我们自己定义了一个连接池,用池来管理Connection,这样可以重复使用Connection,有了池,我们就不用自己来创建Connection,而是通过池来获取Connection对象,当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池,池也就可以再利用这个Connection对象。

创建自定义连接池的步骤

1 创建连接池实现(数据源),并实现接口javax.sql.DataSource.

2 提供一个集合,用于存放连接,因为移除/添加操作过多,所以选用LinkedList较好

3 为连接池初始化连接

4 程序如果需要连接,调用实现类的getConnection(),本方法将从连接池(容器List)获取连接,为了保证当前连接只是停工给一个线程使用,我们需要将连接先从连接池中移除。

5 当用户使用完连接,释放资源时,不执行close()方法,而是将连接添加到连接池中

自定义连接池的代码:

 package com.baidu.database.tools;

 import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
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; /**
* 自定义连接池
*
* @author Admin
*
*/
public class MyDatabasePool implements DataSource { /**
* 创建集合存放连接
*/
public LinkedList<Connection> list = new LinkedList<>(); // 使用构造方法初始化连接池
public MyDatabasePool() throws Exception {
// 创建最小连接数个数据库连接对象以备使用
for (int i = 1; i < 21; i++) {
// 将创建好的数据库连接对象添加到Linkedlist集合中
list.add(JdbcUtils.getConnection());
}
} @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;
} /**
* 获取链接 通过动态代理(Proxy)实现的数据库连接池的创建连接与归还链接的操作
*/
@Override
public Connection getConnection() throws SQLException {
Connection connection = list.removeLast();
//创建代理对象
Connection proxyConnection = (Connection) Proxy.newProxyInstance(
//类加载器
connection.getClass().getClassLoader(),
//目标接口对象
new Class[] { Connection.class },
//当调用connction对象的时候自动触发事务处理器
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//判断执行close()就把连接放入连接池
if ("close".equals(method.getName())) {
//连接放入连接池
list.addLast(connection);
return null;
} else {
//调用目标方法对象
return method.invoke(connection, args);
} }
});
return proxyConnection; } @Override
public Connection getConnection(String username, String password) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
} }
          JdbcUtils地址

★测试增删改查:

 package com.baidu.database.test;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.baidu.database.tools.JdbcUtils;
import com.baidu.database.tools.MyDatabasePool; public class MySouceTest { // 初始化value
static MyDatabasePool database = null;
static Connection connection = null;
static PreparedStatement statement = null;
static ResultSet result = null;
@Before
public void StartDocument() throws Exception {
// 创建自定义数据库对象
database = new MyDatabasePool();
} @After
public void end() throws Exception {
// 关闭链接
JdbcUtils.close(connection, statement, result);
System.out.println("关闭链接");
} @Test
/**
* 测试添加功能
*
* @throws Exception
*/
public void addTest() throws Exception {
// 获取链接
connection = database.getConnection();
// 书写SQL语句
String sql = "insert into test01 values(?,?)";
// 使用prepareStatement对象进行预编译
statement = connection.prepareStatement(sql);
// 设置参数
statement.setInt(1, 1);
statement.setString(2, "张三");
// 获取结果
int result = statement.executeUpdate(); if (result != 0) {
System.out.println("success");
}
} @Test
/**
* 测试删除功能
*
* @throws Exception
*/
public void delTest() throws Exception {
// 获取链接
connection = database.getConnection();
// 书写SQL语句
String sql = "delete from test01 where id=?";
// 使用prepareStatement对象进行预编译
statement = connection.prepareStatement(sql);
// 设置参数
statement.setInt(1, 1);
// 获取结果
int result = statement.executeUpdate(); if (result != 0) {
System.out.println("success");
}
} @Test
public void updateTest() throws Exception {
// 获取链接
connection = database.getConnection();
// 书写SQL语句
String sql = "update test01 set name=? where id=?";
// 使用prepareStatement对象进行预编译
statement = connection.prepareStatement(sql);
// 设置参数
statement.setString(1, "admin");
statement.setInt(2, 1);
// 获取结果
int result = statement.executeUpdate(); if (result != 0) {
System.out.println("success");
}
} @Test
/**
* 测试查询全部
*
* @throws Exception
*/
public void selectTest() throws Exception { // 创建链接
connection = database.getConnection();
if (connection == null) {// 判断是否获取到了链接
return;
}
// 书写SQL
String sql = "select id,name from test01 where id=?";
// 预编译SQL
statement = connection.prepareStatement(sql);
// 设置参数
statement.setInt(1, 1);
// 获取结果集
result = statement.executeQuery(); if (result.next()) {
System.out.println("successful");
} }
}

  这就是自定义一个简单的JDBC连接池实现方法,希望能给大家一个参考,也希望大家多多支持我。

05-11 16:55