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

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();
        }
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值