温馨提示×

java的mysql连接池怎么写

九三
193
2021-02-14 19:47:52
栏目: 云计算
亿速云mysql数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

java的mysql连接池怎么写

利用java编写mysql连接池的方法

具体内容如下:

public class ConnecionPool {

private int size;

List connections = new ArrayList<>();

public ConnecionPool(int size){

this.size=size;

init();

}

public void init(){

try {

Class.forName("com.mysql.jdbc.Driver");

while (size--!=0){

connections.add(DriverManager.getConnection(jdbc:mysql://127.0.0.1:3306/d数据库名称, 用户名,密码)// );

}

}catch (Exception e){

e.printStackTrace();

}

}

public Connection getConnection(){

try {//如果没有连接了,线程就等待

while (connections.isEmpty()){

this.wait();

}

}catch (Exception e){

e.printStackTrace();

}

return connections.remove(0);

}

public void returnConntion(Connection connection){

connections.add(connection);

this.notifyAll();

}

}

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

推荐阅读:Java连接MySQL提示连接池满了怎么解决

0