可以从PreparedStatement中提取Sql的类LoggableStatement

xiaoxiao2021-03-01  19

本人只是根据原类稍作修改... 实现原理: 重新实现PreparedStatement接口.定义两个辅助变量:sqlTemplate和parameterValues sqlTemplate带有?的Sql,parameterValues存放参数值,是一个ArrayList.然后在每个set方法中调用saveQueryParamValue 方法设置parameterValues列表... 替换?为参数值的方法: java 代码 public String getQueryString() {               StringBuffer buf = new StringBuffer();            int qMarkCount = 0;            StringTokenizer tok = new StringTokenizer(sqlTemplate+" ""?");            while (tok.hasMoreTokens()) {                String oneChunk = tok.nextToken();                buf.append(oneChunk);                   try {                    Object value;                    if (parameterValues.size() > 1 + qMarkCount) {                        value = parameterValues.get(1 + qMarkCount++);                    } else {                        if (tok.hasMoreTokens()) {                            value = null;                        } else {                            value = "";                        }                    }                    buf.append("" + value);                } catch (Throwable e) {                    buf.append(                        "ERROR WHEN PRODUCING QUERY STRING FOR LOG."                           + e.toString());                    // catch this without whining, if this fails the only thing wrong is probably this class                }            }            return buf.toString().trim();        }   

初始化参数列表的方法:

java 代码 private void saveQueryParamValue(int position, Object obj) {            String strValue;            if (obj instanceof String || obj instanceof Date) {                // if we have a String or Date , include '' in the saved value                strValue = "'" + obj + "'";            } else {                   if (obj == null) {                    // convert null to the string null                    strValue = "null";                } else {                    // unknown object (includes all Numbers), just call toString                    strValue = obj.toString();                }            }               // if we are setting a position larger than current size of parameterValues, first make it larger            while (position >= parameterValues.size()) {                parameterValues.add(null);            }            // save the parameter            parameterValues.set(position, strValue);        }   相关资源:自动抢茅台脚本.zip
转载请注明原文地址: https://www.6miu.com/read-3850320.html

最新回复(0)