All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cq.database.helper.SQLHelper Maven / Gradle / Ivy

The newest version!
package cq.database.helper;

import cq.database.util.ThisUtil;

import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SQLHelper {
    public static String keyFormat(String s, Object obj) {
        String regex = "\\{[A-Za-z_$][A-Za-z_$\\\\d]*\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);
        Class clazz = obj.getClass();
        Set keySet = new HashSet<>();
        while (matcher.find()) {
            keySet.add(matcher.group(0));
        }
        for (String temp : keySet) {
            String key = temp.substring(1, temp.length() - 1);
            String rep = "\\{" + key + "\\}";
            try {
                Field field = clazz.getDeclaredField(key);
                field.setAccessible(true);
                Object o = field.get(obj);
                if (o == null) {
                    s = s.replaceAll(rep, "''");
                } else if (o instanceof Date) {
                    s = s.replaceAll(rep, "'" + ThisUtil.date2Str((Date) o, "yyyy-MM-dd HH:mm:ss") + "'");
                } else if (!ThisUtil.isNumber(o)) {
                    s = s.replaceAll(rep, "'" + o + "'");
                } else {
                    s = s.replaceAll(rep, o + "");
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
                s = s.replaceAll(rep, "''");
            }
        }
        return s;
    }

    public static String indexFormat(String s, Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (objects[i] == null) {
                s = s.replaceAll("\\{" + i + "\\}", "''");
            } else {
                if (objects[i] instanceof Date) {
                    objects[i] = ThisUtil.date2Str((Date) objects[i], "yyyy-MM-dd HH:mm:ss");
                }
                if (ThisUtil.isNumber(objects[i])) {
                    s = s.replaceAll("\\{" + i + "\\}", objects[i] + "");
                } else {
                    s = s.replaceAll("\\{" + i + "\\}", "'" + objects[i] + "'");
                }
            }
        }
        return s;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy