可以从PreparedStatement中提取Sql的类LoggableStatement

    技术2022-05-11  63

    本人只是根据原类稍作修改...实现原理:重新实现PreparedStatement接口.定义两个辅助变量:sqlTemplate和parameterValuessqlTemplate带有?的Sql,parameterValues存放参数值,是一个ArrayList.然后在每个set方法中调用saveQueryParamValue方法设置parameterValues列表...替换?为参数值的方法:

    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();    }

     初始化参数列表的方法:

    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);    }

    最新回复(0)