JAVA通过Map拼接SQL语句(Insert Update语句)
package com.lynch.erp.core.util;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
public class SQLUtils {
/**
* 通过Map拼接Insert SQL语句
*
* @param tableName
* @param dataMap
* @return
*/
public static String genSqlInsert(String tableName, Map<String, String> dataMap) {
if(MapUtils.isEmpty(dataMap)) {
return null;
}
//生成INSERT INTO table(field1,field2) 部分
StringBuffer sbField = new StringBuffer();
//生成VALUES('value1','value2') 部分
StringBuffer sbValue = new StringBuffer();
sbField.append("INSERT INTO " + tableName.toLowerCase() + "(");
for(Map.Entry<String, String> entry : dataMap.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
if(StringUtils.equals(mapKey, CamelUnderlineUtil.PK)) {
continue;
}
sbField.append("`" + mapKey + "`,");
sbValue.append("'" + mapValue + "',");
}
sbField = Util.deleteLastChar(sbField);
sbValue = Util.deleteLastChar(sbValue);
return sbField.toString() + ") VALUES(" + sbValue.toString() + ")";
}
/**
* 通过Map拼接Update SQL语句
*
* @param tableName
* @param operation
* @param dataMap
* @return
*/
public static String genSqlUpdate(String tableName, Map<String, String> dataMap) {
if(MapUtils.isEmpty(dataMap)) {
return null;
}
String idColumn = dataMap.get(CamelUnderlineUtil.PK);
String idValue = dataMap.get(idColumn);
StringBuffer sb = new StringBuffer();
sb.append("UPDATE "+ tableName.toLowerCase() +" SET ");
for(Map.Entry<String, String> entry : dataMap.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
if(StringUtils.equals(mapKey, CamelUnderlineUtil.PK)) {
continue;
}
if(StringUtils.equals(mapKey.toLowerCase(), idColumn)) {
continue;
}
sb.append("`" + mapKey + "`='" + mapValue + "',");
}
sb = Util.deleteLastChar(sb);
return String.format("%s where %s='%s'", sb.toString(), idColumn, idValue);
}
}