package com.xydl.cac.util;

import org.apache.commons.lang3.StringUtils;


public class SqlEscapeUtil {
    /**
     * 转义字符
     **/
    public static final char ESCAPE = '!';

    /**
     * 转义方法
     *
     * @param param 待转义字符串
     * @return String
     */
    public static String escape(String param) {
        if (StringUtils.isNotEmpty(param)) {
            String temp = param.replaceAll("/", ESCAPE + "/");
            temp = temp.replaceAll("%", ESCAPE + "%");
            temp = temp.replaceAll("_", ESCAPE + "_");
            temp = temp.replaceAll("'", "''");
            return temp.trim();
        }
        return "";
    }

    public static boolean sqlValidate(String str) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        str = str.toLowerCase();// 统一转为小写
        String badStr = "'|exec|and|or|execute|insert|select|delete|update|drop|%|master|truncate|"
                + "declare|sitename|net user|xp_cmdshell|like'|exec|execute|insert|create|drop|"
                + "table|grant|use|group_concat|column_name|information_schema.columns|table_schema|"
                + "select|delete|update|master|truncate|declare|-- |like|//|%";// 过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|");
        for (String s : badStrs) {
            if (str.contains(s)) {
                return true;
            }
        }
        return false;
    }
}
