package designpattern.pool;
import designpattern.staticagent.MyConnecntion;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ConnectionPool {
private static List<Connection> connections=new ArrayList<>();
static {
for (int i=0;i<10;i++){
//可以考虑dbcp,c3p0的配置,进行设置
Connection connection=new MyConnecntion();
connections.add(connection);
}
}
public static synchronized Connection getConnection() throws SQLException {
for(Connection connection:connections){
MyConnecntion myConnecntion=(MyConnecntion)connection;
if(!myConnecntion.isClosed()){
return myConnecntion;
}
}
//尝试等待一会在获取
return null;
}
public static synchronized void closeConnections(){
for(Connection connection:connections){
MyConnecntion myConnecntion=(MyConnecntion)connection;
myConnecntion.setClose(true);
}
}
}
package designpattern.pool;
import java.sql.ResultSet;
public interface RwoMapper {
Object mapRow(ResultSet resultSet);
}
package designpattern.pool;
import javax.swing.tree.RowMapper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCTemplate {
public void update(String sql,String...params){
try {
Connection connection=ConnectionPool.getConnection();
connection.prepareStatement(sql,params);
PreparedStatement preparedStatement=connection.prepareStatement(sql);
for (int i=0;i<params.length;i++){
preparedStatement.setString(i+1,params[i]);
}
int res=preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void query(String sql,RwoMapper rowMapper, String...params){
try {
Connection connection=ConnectionPool.getConnection();
connection.prepareStatement(sql,params);
PreparedStatement preparedStatement=connection.prepareStatement(sql);
for (int i=0;i<params.length;i++){
preparedStatement.setString(i+1,params[i]);
}
ResultSet resultSet=preparedStatement.executeQuery();
if(resultSet!=null){
while (resultSet.next()){
rowMapper.mapRow(resultSet);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
来源:CSDN
作者:红豆和绿豆
链接:https://blog.csdn.net/u011955252/article/details/104669865