CachedPreparedStatement

CachedPreparedStatement是一个PreparedStatement的增强工具类,可以先将sql和替换条件放到CachedPreparedStatement里,等需要PreparedStatement时再将条件替换占位符,项目中,我是没用这个工具类,而是直接使用PreparedStatement的setXXX方法设置的,不知道其他人用没,姑且留个纪念吧!

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;


/**
 * Allows PreparedStatement information to be cached. A prepared statement consists of
 * a SQL statement containing bind variables as well as variable values. For example,
 * the SQL statement <tt>"SELECT * FROM person WHERE age > ?"</tt> would have the integer
 * variable <tt>18</tt> (which replaces the "?" chracter) to find all adults. This class
 * encapsulates both the SQL string and bind variable values so that actual
 * PreparedStatement can be created from that information later.
 *
 * @author Matt Tucker
 */
public class CachedPreparedStatement  {

    private String sql;
    private List<Object> params;
    private List<Integer> types;

    /**
     * Constructs a new CachedPreparedStatement.
     */
    public CachedPreparedStatement() {
        params = new ArrayList<Object>();
        types = new ArrayList<Integer>();
    }

    /**
     * Constructs a new CachedPreparedStatement.
     *
     * @param sql the SQL.
     */
    public CachedPreparedStatement(String sql) {
        this();
        setSQL(sql);
    }

    /**
     * Returns the SQL.
     *
     * @return the SQL.
     */
    public String getSQL() {
        return sql;
    }

    /**
     * Sets the SQL.
     *
     * @param sql the SQL.
     */
    public void setSQL(String sql) {
        this.sql = sql;
    }

    /**
     * Adds a boolean parameter to the prepared statement.
     *
     * @param value the boolean value.
     */
    public void addBoolean(boolean value) {
        params.add(value);
        types.add(Types.BOOLEAN);
    }

    /**
     * Adds an integer parameter to the prepared statement.
     *
     * @param value the int value.
     */
    public void addInt(int value) {
        params.add(value);
        types.add(Types.INTEGER);
    }

    /**
     * Adds a long parameter to the prepared statement.
     *
     * @param value the long value.
     */
    public void addLong(long value) {
        params.add(value);
        types.add(Types.BIGINT);
    }

    /**
     * Adds a String parameter to the prepared statement.
     *
     * @param value the String value.
     */
    public void addString(String value) {
        params.add(value);
        types.add(Types.VARCHAR);
    }

    /**
     * Sets all parameters on the given PreparedStatement. The standard code block
     * for turning a CachedPreparedStatement into a PreparedStatement is as follows:
     *
     * <pre>
     * PreparedStatement pstmt = con.prepareStatement(cachedPstmt.getSQL());
     * cachedPstmt.setParams(pstmt);
     * </pre>
     *
     * @param pstmt the prepared statement.
     * @throws java.sql.SQLException if an SQL Exception occurs.
     */
    public void setParams(PreparedStatement pstmt) throws SQLException {
        for (int i=0; i<params.size(); i++) {
            Object param = params.get(i);
            int type = types.get(i);
            // Set param, noting fact that params start at 1 and not 0.
            switch(type) {
                case Types.INTEGER:
                    pstmt.setInt(i+1, (Integer)param);
                    break;
                case Types.BIGINT:
                    pstmt.setLong(i+1, (Long)param);
                    break;
                case Types.VARCHAR:
                    pstmt.setString(i+1, (String)param);
                    break;
                case Types.BOOLEAN:
                    pstmt.setBoolean(i+1, (Boolean)param);
            }
        }
    }

    @Override
	public boolean equals(Object object) {
        if (object == null) {
            return false;
        }
        if (!(object instanceof CachedPreparedStatement)) {
            return false;
        }
        if (this == object) {
            return true;
        }
        CachedPreparedStatement otherStmt = (CachedPreparedStatement)object;
        return (sql == null && otherStmt.sql == null) || sql != null && sql.equals(otherStmt.sql)
                && types.equals(otherStmt.types) && params.equals(otherStmt.params);
    }

    @Override
	public int hashCode() {
        int hashCode = 1;
        if (sql != null) {
            hashCode += sql.hashCode();
        }
        hashCode = hashCode * 31 + types.hashCode();
        hashCode = hashCode * 31 + params.hashCode();
        return hashCode;
    }

    @Override
	public String toString() {
        String toStringSql = sql;
        try {
            int index = toStringSql.indexOf('?');
            int count = 0;

            while (index > -1) {
                Object param = params.get(count);
                int type = types.get(count);
                String val = null;

                // Get param
                switch(type) {
                    case Types.INTEGER:
                        val = "" + param;
                        break;
                    case Types.BIGINT:
                        val = "" + param;
                        break;
                    case Types.VARCHAR:
                        val =  '\'' + (String) param + '\'';
                        break;
                    case Types.BOOLEAN:
                        val = "" + param;
                }

                toStringSql = toStringSql.substring(0, index) + val +
                        ((index == toStringSql.length() -1) ? "" : toStringSql.substring(index + 1));
                index = toStringSql.indexOf('?', index + val.length());
                count++;
            }
        }
        catch (Exception e) {
        	e.printStackTrace();
        }

        return "CachedPreparedStatement{ sql=" + toStringSql + '}';
    }
    
    public static void main(String[] args) {
    	String sql = "select * from test where id = ? and name = ?";
    	CachedPreparedStatement cps = new CachedPreparedStatement(sql);
    	cps.addInt(1); //按顺序替换的,如果和下面的交换则会将123赋给id
    	cps.addString("123");
    	System.out.println(cps.toString());
		//打印结果:CachedPreparedStatement{ sql=select * from test where id = 1 and name = '123'}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值