import java.util.*;java
public class SQLDemo {
public static String sqlCommon="";
//模擬寫sql語句
public static String querySQL(Map<String,Object> map,String tableName){
//map如有參數查詢則size從1開始算起
if (map.isEmpty()||map.size()==0) {
sqlCommon = "select * from "+tableName;
} else {
sqlCommon = "select * from "+tableName+" where ";
//再進行拼接sql語句回去
//若是隻有一個則不用添加and 如有多個參數則再設計
Set set = map.keySet();
Iterator iterable = set.iterator();
int index = 0;//默認下標爲零,其做用是判斷是否與map的最後一個參數相等從而去掉and
while(iterable.hasNext()){
String key = (String)iterable.next();
Object value = map.get(key);
//判斷類型
if (value instanceof String) {value="'"+value+"'";}
index++;
//僅有一個參數或是最後一個參數
if ( ( index==1&&map.size()==1)||map.size()==index) {
sqlCommon += key + "="+value+" ";
} else {
//Constants.SQL.ADD 和 and是同樣的
//sqlCommon += key+"="+value+" "+ Constants.SQL.ADD +" ";
sqlCommon += key+"="+value+" "+ "and" +" ";
}
}
}
return sqlCommon;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Object> map = new HashMap<String, Object>();
//存放值和類型標識
map.put("stuName","張三");
map.put("classid",123456);
map.put("age",23);
String tableName="Student";
System.out.println(querySQL(map,tableName).toString());
}
}sql