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);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。










