public class MyDateSource {
private String url = "jdbc:mysql://localhost:3306/2207b";
private String username="root";
private String password="Root123456";
//第一步:要声明一个LinkedList集合(连接池)
private LinkedList<Connection>connections=new LinkedList<>();
//第二步:初始化:创建5个连接(构造函数,静态代码块)
public MyDateSource(){
for(int i=1; i<=5;i++){
try{
//创建连接
Connection connection= DriverManager.getConnection(url,username,password);
//将连接存入连接池(集合)
onnections.add(connection);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
}
//第三步:如果连接池中有连接,获取连接池中连接,如果没有,就创建新的连接
public Connection getConnection(){
Connection connection=null;
if (connections.size()>0){
System.out.println("连接池获取");
connection=connections.removeFirst();
}else {
System.out.println("连接池没有连接,重新创建");
try{
connection= DriverManager.getConnection(url,username,password);
}catch(SQLException e){
throw new RuntimeException(e);
}
}
return connection;
}
public void addBack(Connection connection){
connections.addLast(connection);
}
}