JAVA 对象集合转换为SQL

JAVA 对象集合转换为SQL

对象集合是从别数据库获得,有的字段是null(或者根据其他要求),转换为insert SQL语句,用于存储过程(数据量较大时使用)。
1. 根据一个对象,获取对象的属性类型,属性名称,属性值得集合;
public List getFiledsInfo(Object o){
Field[] fields=o.getClass().getDeclaredFields();
String[] fieldNames=new String[fields.length];
List list = new ArrayList();
Map infoMap=null;
for(int i=0;i小于fields.length;i++){
infoMap = new HashMap();
infoMap.put(“type”, fields[i].getType().toString());
infoMap.put(“name”, fields[i].getName());
infoMap.put(“value”, getFieldValueByName(fields[i].getName(), o));
list.add(infoMap);
}
return list;
}
2. 根据对象的属性名,获取对象相应的属性值;
public Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = “get” + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
return null;
}
}
3. 指定表名,拼写SQL(空值得跳过);
public List insertSqlList(String tableName, List quanlifylist) {
List sqlList = new ArrayList();
for(int i = 0 ;i小于quanlifylist.size();i++){
List list = getFiledsInfo(quanlifylist.get(i));
String values = “”;
String fields = “”;
for(int j = 0 ;j小于list.size();j++){
if (list.get(j) != null) {
// 拼写sql
Map map = (Map)list.get(j);
String name = map.get(“name”).toString();
String type = map.get(“type”).toString();
Object value = map.get(“value”);

// fields += name + “,”;
if (type != null && null!=value) {
fields += name + “,”;
if (type.contains(“Integer”) ||type.contains(“Double”)) {
values += value + “,”;
} else if (type.contains(“DATE”)) {
if (value instanceof Date) {
SimpleDateFormat sf = new SimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”);
value = sf.format(value);
}
values += “to_date(‘” + value
+ “’,’yyyy-MM-dd hh24:mi:ss’),”;
} else {
if(value.toString().contains(“’”)){
value = value.toString().replaceAll(“’”, “””);
values += “’” + value + “’,”;
}else{
values += “’” + value + “’,”;
}
}
}
}
}
fields = fields.substring(0, fields.length()-1);
values = values.substring(0, values.length()-1);
String sql = “insert into ” + tableName + “(” + fields
+ “) values(” + values + “)”;
sqlList.add(sql);
}
return sqlList;
}

帮助可以查看连接

你可能感兴趣的:(拼接SQL)