package com.yanzuoguang.db.impl; import com.yanzuoguang.db.DbPrintSql; import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.log.Log; import org.springframework.stereotype.Component; /** * 打印Sql语句 * * @author 颜佐光 */ @Component public class DbPrintSqlDefault implements DbPrintSql { @Override public void printSql(SqlInfo sqlInfo, long time, int row) { String sql = getStringSql(sqlInfo.getSql(), sqlInfo.getParas()); // 打印SQL语句 String tag = String.format("%d row %d ms %s.%s", row, time, sqlInfo.getTargetClass().getSimpleName(), sqlInfo.getSqlName()); Log.infoTag(DbExecutePrintSql.class, tag, sql); } /** * 获取参数处理之后的SQL语句 * * @param sql 带参数的SQL语句 * @param paras 参数 * @return 不带参数的SQL语句 */ public String getStringSql(String sql, Object... paras) { StringBuilder sb = new StringBuilder(); // 进行SQL语句参数替换,后面增加一个空格,方便后续用正则表达式进行替换处理 String[] split = sql.split("\\?"); // 参数位置 int pos = 0; // 循环获取参数 while (pos < split.length) { // 获取位置信息 sb.append(split[pos]); // 获取位置 if (pos == split.length - 1) { break; } // 获取对象 Object item = paras.length > pos ? paras[pos] : null; String str = StringHelper.toString(item); String strTo = str; if (str == null) { strTo = "null"; } else if (item instanceof Number || item.getClass().isEnum() || item instanceof Boolean) { // 不进行处理 } else { strTo = "'" + str.replace("'", "''") + "'"; } sb.append(strTo); pos++; } return sb.toString(); } }