编码调试过程中,常有Sql语句的调试任务,这种任务比较麻烦的一点在于需要手工将?替换成参数,如果参数有十来个就够让人头疼的.
为了减轻这种无谓的劳动,本人设计了一个类来代替完成这种累而又容易让人出错的活.
下面是代码:
package com.heyang;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 将SQL语句中的问号替换成参数
 * 此类用于调试SQL时减轻手工加入参数的劳动量
 * @author heyang@gmail.com
 *
 */
public class SqlCompletion{
    // 输入的SQL语句
    private String sql;
    
    // 输入的参数
    private String[] arr;
    
    // 构造函数
    public SqlCompletion(String sql,Object[] params){
        this.sql=sql;
        
        arr=new String[params.length];
        
        for(int i=0;i<arr.length;i++){
            arr[i]="'"+params[i].toString()+"'";
        }
    }
    
    /**
     * 取得将问号替换成参数的补全SQL
     * @return
     */
    public String getCompletedSql(){
        Pattern p = Pattern.compile("\\?",Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(sql);
        StringBuffer sb = new StringBuffer();
        boolean result = m.find();
        int index=0;
        while (result) {
            m.appendReplacement(sb, "{"+index+"}");
            index++;
            result = m.find();
        }
        m.appendTail(sb);
        String repSql=sb.toString();
        
        return MessageFormat.format(repSql,arr);
    }
    
    // 测试
    public static void main(String[] args){
        Object[] params={"c1","c2","c3","c4"};
        SqlCompletion s=new SqlCompletion("select * from t where t.f1=? and t.f2=? and t.f3=? and t.f4=? ",params);
        System.out.println(s.getCompletedSql());        
    }
}
输出结果是:
select * from t where t.f1='c1' and t.f2='c2' and t.f3='c3' and t.f4='c4'
你可以把此类拷贝到你的项目中,只要标明我是原作者就行.