/**
* 使用连接池连接数据库
* @author
*/
public class MyDataSource implements DataSource {
//1.创建容器用于放置的Connection对象--因为频繁的操作添加和删除所以使用LinkedList对象
private static LinkedList<Connection> ls = new LinkedList<>();
static {
//创建连接并添加到容器中
for (int i = 0; i <= 6; i++) {
//获取连接
Connection conn = JdbcUtils.getConnection();//此时连接方法、已经封装成工具类
ls.add(conn);
}
}
@Override
public Connection getConnection() throws SQLException {
Connection conn = null;
if (ls.size() == 0) {
for (int i = 0; i <= 6; i++) {
//获取连接
conn = JdbcUtils.getConnection();
//添加Connection对象到linkedList对象
ls.add(conn);
}
}
//拿到一个Connection对象
conn = ls.removeFirst();
return conn;
}
/**
* 调用完之后放回容器--释放资源
* @param conn
*/
public static void addSqlClose(Connection conn) {
if(conn != null)
ls.add(conn);
}
@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 {
return null;
}
@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;
}
}
注意:上面是实现了DataSource 接口,所以要覆写接口中的方法,这里由于时间的问题,只覆写了getConnection方法