DBPool.java
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* 数据库连接池类
* 1. 类加载时需要产生30个数据库连接
* 2. 提供获取连接方法
* 3. 能扩容(增加5个连接)
* 4. 提供归还连接方法
*/
public class DBPool implements DataSource {
List<Connection> list = new ArrayList<>();
public DBPool() throws Exception {
for (int i = 0; i < 30; i++) {
list.add(DBUtil.getInstance().getConnection());
}
}
@Override
public Connection getConnection() throws SQLException {
// 扩容
if (list.size() == 0) {
for (int i = 0; i < 5; i++) {
try {
Connection conn = DBUtil.getInstance().getConnection();
list.add(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// remove(0)表示弹出集合中第一个元素
return list.remove(0);
}
/**
* 归还连接
* @param conn
* @return true成功 false失败
*/
public boolean giveBackConn(Connection conn) {
return list.add(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;
}
}
网友评论