更新数据库的共通类
package updateCommon;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class CommonUpdate {
/**
* author: YSM
* <p>Title: update</p>
* <p>Description: 更新数据库表,共通方法</p>
* @param updateMap 需要更新的字段
* @param qualificationMap 更新条件
* @param tableName 更新的表名
*/
public static void update(Map<String, String> updateMap, Map<String, String> qualificationMap, String tableName) {
Set<String> updateSet = updateMap.keySet();
Iterator<String> updateIt = updateSet.iterator();
String updateKey = null;
StringBuffer updateSql = new StringBuffer("");
while (updateIt.hasNext()) {
updateKey = updateIt.next();
String[] tempStr = dealKeyAndValueByDataType(updateKey, updateMap);
updateSql.append(tempStr[0]);
updateSql.append(" = ");
updateSql.append(tempStr[1]);
if (updateIt.hasNext()) {
updateSql.append(" , ");
}
}
Set<String> qualificationSet = qualificationMap.keySet();
Iterator<String> qualificationIt = qualificationSet.iterator();
StringBuffer qualificationSql = new StringBuffer("");
String qualificationKey = null;
if (qualificationIt.hasNext()) {
qualificationSql.append(" where ");
}
while (qualificationIt.hasNext()) {
qualificationKey = qualificationIt.next();
String[] tempStr = dealKeyAndValueByDataType(qualificationKey, qualificationMap);
qualificationSql.append(tempStr[0]);
qualificationSql.append(" = ");
qualificationSql.append(tempStr[1]);
if (qualificationIt.hasNext()) {
qualificationSql.append(" and ");
}
}
String sql = "update " + tableName + " set " + updateSql + qualificationSql;
System.out.println(sql);
}
private static String[] dealKeyAndValueByDataType(String str, Map<String, String> qualificationMap) {
String [] tempStr = str.split("_");
String [] returnStr = new String[2];
returnStr[0] = tempStr[1];
if ("char".equals(tempStr[0])) {
returnStr[1] = "'" + (String)qualificationMap.get(str) + "'";
} else if ("int".equals(tempStr[0])) {
returnStr[1] = (String) qualificationMap.get(str);
}
return returnStr;
}
public static void main (String [] args) {
Map<String, String> updateMap = new HashMap<String, String>();
updateMap.put("int_id", "1");
updateMap.put("char_name", "ysm");
Map<String, String> qualificationMap = new HashMap<String, String>();
qualificationMap.put("int_sn", "4");
qualificationMap.put("char_osn", "12345abc");
update(updateMap, qualificationMap, "t_repair");
}
}