編碼調(diào)試過程中,常有Sql語句的調(diào)試任務(wù),這種任務(wù)比較麻煩的一點在于需要手工將?替換成參數(shù),如果參數(shù)有十來個就夠讓人頭疼的.
為了減輕這種無謂的勞動,本人設(shè)計了一個類來代替完成這種累而又容易讓人出錯的活.
下面是代碼:
package com.heyang;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 將SQL語句中的問號替換成參數(shù)
* 此類用于調(diào)試SQL時減輕手工加入?yún)?shù)的勞動量
* @author heyang@gmail.com
*
*/
public class SqlCompletion{
// 輸入的SQL語句
private String sql;
// 輸入的參數(shù)
private String[] arr;
// 構(gòu)造函數(shù)
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()+"'";
}
}
/**
* 取得將問號替換成參數(shù)的補全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());
}
}
輸出結(jié)果是:
select * from t where t.f1='c1' and t.f2='c2' and t.f3='c3' and t.f4='c4'
你可以把此類拷貝到你的項目中,只要標明我是原作者就行.