设计模式--池技术与策略模式

百般思念 提交于 2020-03-06 02:10:10
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();
        }
    }


}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!